jQuery Element Selector allows us to select an element from the html page based on the element name. In this guide, we will learn how to use element selector in jQuery. If you are not sure what is a selector, refer this guide: jQuery Selector.
Syntax
$("element_name")
We can provide the element name that we want to select in the parenthesis. For example $(“h2”) will select all h2 element of the html page, similarly $(“p”) will select all the paragraph elements of the page.
jQuery Element Selector Example
Lets take an example to understand the usage of element name selector. In the following example, we are selecting all the paragraphs of an html page and hiding them on the button click event.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); }); </script> </head> <body> <h2>jQuery Element name selector example</h2> <p>This tutorial is published on beginnersbook.com website</p> <p>This is another para and it contains some text.</p> <button>Click Me!</button> </body> </html>
Output:
Before the button click event:
After the button click event:
jQuery Element Selector – Selecting all p elements with class “main”
In the above example we have used element selector to select an element whose name is passed in the parenthesis inside $(). In this example, we will use the element name along with the class, which will help us select all those element with the specified class. You can also refer jQuery class selector to understand how a class is used in selector.
In the following example on the button click event, we are selecting all those paragraphs that have class “main” and changing the background colour to green.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p.main").css("background-color", "green"); }); }); </script> </head> <body> <h2>jQuery Element name selector example</h2> <p class="main">This tutorial is published on beginnersbook.com website</p> <p>This is another para and it contains some text.</p> <p class="main">This is my third paragraph.</p> <button>Click Me!</button> </body> </html>
Output:
Before the button is clicked:
After the button is clicked:
Leave a Reply