ID Selector in jQuery

jqueryIn HTML, each element can have its unique ID.  This unique ID is further used by JavaScript and jQuery for manipulation.  Having a unique ID for each element will make easy for jQuery and JavaScript to find the right HTML element in DOM.  In jQuery, we use hash (#) in front of ID for selection, like $(‘#ElementID’) and in JavaScript, we simply use document.getElementById function by passing ID as parameter.  However, behind the scenes, jQuery uses getElementByID function for selection.

GetElementByID returns a raw DOM object whereas jQuery selector wraps raw DOM object and returns jQuery object.  Thus, we can make use of all the functions and properties provided by jQuery like css, click etc.  GetElementByID is faster than jQuery ID selector because there is no wrapping involved.  To get underlying DOM object, we add index position of element after jQuery selector. For example: $(‘ElementID’) [0]

In HTML, there is a possibility that we will have 2 or more HTML elements with same ID.  In such a scenario, jQuery selector will return only first element.  In case of JavaScript, if element is not found of specified ID, it will throw an error, but not in jQuery.  To be on safe side, we make use of length property of jQuery selector to check if an element is found or not before code execution.  Example of jQuery ID selector is given below.

<html>
<head>
<title>jQuery Tutorial </title>
 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 
 $(document).ready(function () {
    
    $('#myBtn').click( function(){
        
        alert("hello");
    });
 });
 
</script>
</head>

<body>
 
<input type="button" id="myBtn" value="Click Me" />

</body>
</html>