To get an element by its ID using jQuery, you can use the #
symbol followed by the ID of the element in a selector. Here’s an example:
HTML code:
<div id="myDiv">This is my div</div>
jQuery code:
$(document).ready(function() {
var myDiv = $('#myDiv');
console.log(myDiv.text());
});
In the code above, the #
symbol is used to select the element with the ID myDiv
and the text()
method is used to get the text content of the selected element. The selected element is then assigned to the variable myDiv
.
Note that the above code assumes that you have included the jQuery library in your HTML file. If you haven’t done so, you can add the following script tag before the jQuery code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
This will include the jQuery library from a CDN (Content Delivery Network).