jQuery

Examples To Get Div Text Using Div ID / Div Class in jQuery

While working with many elements of a web page, especially divs, there might have been a time when you felt the need to get the div text using jQuery. So do you know how to get it? If not, then this article is for you. In this article, I am going to share very easy ways to use jQuery to get div text by means of div ID and div Class name. Demo & Examples are included, so it will be super easy & fun to follow along.

Examples on how to Get Div Text Using Div ID / Div Class Name

Simply put, the div text is nothing but the content of the div. So for the sake of the example, let us assume that we have a div in our webpage. It has an ID “my_div_id” and a class “my_div_class”.  So here’s what we are going to do. We are going to create 2 buttons. When one button is clicked, it will alert the div text by targeting the div using it’s ID. The second button will also alert the div text, but the only difference is that it will target the div using it’s class. Agreed? So let’s jump to the source code:

Source code to Get Div Text using Div ID & Div Class Name in jQuery:

<html>
<head>
<title>Examples on using jQuery to Get Div Text Using Div ID, Div Class</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
.my_div_class {
	padding: 5px;
	border: 2px solid #09F;
}
</style>
</head>

<body>

<div id="my_div_id" class="my_div_class">This is some custom text in a div.</div>
<br>

<input type="submit" name="sbt_get_div_text_using_id" id="sbt_get_div_text_using_id" value="Get Div Text Using ID">
<input type="submit" name="sbt_get_div_text_using_class_name" id="sbt_get_div_text_using_class_name" value="Get Div Text Using Class Name">
<script type="text/javascript" language="javascript" >
$(document).ready(function(){

	$('#sbt_get_div_text_using_id').click(function(e){

		alert( $('#my_div_id').text() );

		e.preventDefault();

	});		

	$('#sbt_get_div_text_using_class_name').click(function(e){

		alert( $('.my_div_class').text() );

		e.preventDefault();

	});		

});
</script>
</body>
</html>

Your Turn!

Do you know of any other ways to get div text using div id or using div class name in jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*