jQuery Id/Hash (#) Selector With Examples

In this article, I am going to explain the most common jQuery Id/Hash (#) selector With examples. You may see the list of all available selectors here https://api.jquery.com/category/selectors/

Id Selector or Hash (#) Selector

In HTML DOM element ID should be unique for each element. If you want to get an HTML element object you can use Id selector.

Consider a Simple HTML Page with a div and an input text box.

<!DOCTYPE html>
<html>
<head>
	<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
</head>
<body>
<script>
	$( document ).ready(function() {
		var divObj = $("#testdiv"); // Here we got the div obj by id
		console.log(divObj.html());
		
		var inputObj = $("#age");// Here we get the input text by id
		console.log(inputObj.val());

		var objByNative = document.getElementById("testdiv"); //Nativ way to access html element
		console.log(objByNative.innerHTML);

		var divSpecialObj = $("#test\\/div");
		console.log(divSpecialObj.html());
	});
</script>
<h1>jQuery Id Selector</h1>
<div id="testdiv">This is a div, used for testing purpose.</div>
<span>Age: </span> <input type="text" id=age value=10 />
</body>
</html>

In the example above you may see we have access the div and the input by their respective ids. Please note

  1. Html elements ids should be unique for the whole HTML document
  2. Id or Hash selector are case sensitive, if you try to get above div with “TestDiv” it will not return any element because the case is different.

If you are curious about the native Javascript alternate of the hash selector you may use this document.getElementById("testdiv");
if you want to access the content of a div you may use document.getElementById("testdiv").innerHTML

One more important point that you should remember is, if your HTML element’s id contains some special character you should escape. Here is list of special characters.

!"#$%&'()*+,./:;<=>?@[\]^`{|}~

So for example, if your div id is “test/div” you may use Id selector like this. $("#test\/div")

I have used console.log to show the output. If you are using chrome you may press F12 key and open developer tool. In the console tab, you should see the output.

jQuery Id/Hash (#) Selector

That’s it. Above there are a couple of examples, how you can use jQuery Id or Hash (#) selector to get an HTML element object.

Next : Jquery Selector: Find nested/child elements

Please share this post:
Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 10

One thought on “jQuery Id/Hash (#) Selector With Examples

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: