jQuery Id Selector

In jQuery, we can use the id attribute of an HTML element as a selector. The id selector selects a particular element of the matched id. The id attribute value must be unique in a document.

Syntax of id selector

$("#id") 

Here, id is the name of the id attribute of the element to select. This is the required field.

Example

<div id="main">
<p id="para">Hey John!</p>
<p id="ques">
What are you doing these days?
</p>
</div>

<script>
$(document).ready(function(){
$("#main").css("padding", "20px");
$("#main").css("background", "#ffffe0");
$("#para").css("color", "blue");
$("#ques").css("color", "pink");
});
</script>

Output of the above code

Hey John!

What are you doing these days?

In the above example, $("#main") selects the element with an id value 'main' and sets the padding and background color. Similarly, $("#para") sets the font color to blue to the particular element with an id value 'para'.


Example

<div id="somecontent">
 Write some content here.
</div>

<script>
$(document).ready(function(){
$("#somecontent").css("background", "#ffffe0");
$("#somecontent").css("padding", "30px");
$("#somecontent").html("I have added some content here");
});
</script>

Output of the above code

Write some content here.

In the above example, $("#somecontent") selects the element with an id value 'somecontent' and sets the background color and changes the content within it.



Read more articles


General Knowledge



Learn Popular Language