In the previous tutorial, we discussed what are jQuery Selectors. In this guide, we will discuss the jQuery * Selector, which is used to select all the elements of a Document Object Model (DOM). It includes all the elements such as html, head, body etc.
jQuery * Selector Syntax
To select all the elements of html page including html, head, body elements.
$("*")
To select all the child elements of a specified element
$("Element_name *")
jQuery * Selector Example
In the following example we are selecting all the elements of this html page using $(*) selector and when the Click Me! button is clicked we are changing the background colour to green for all the selected elements.
<!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(){ $("*").css("background-color", "green"); }); }); </script> </head> <body> <h2>jQuery * selector example</h2> <p>This example is published on beginnersbook.com</p> <p>This is another paragraph. It contains some plain text</p> <button>Click Me!</button> </body> </html>
Output:
Before the button is clicked: The following is the output of the above code in the browser, the button Click Me! is not yet clicked.
After the button is clicked: The following screenshot is the output screen in the browser after the button is clicked.
jQuery * Selector to select all the child elements of a webpage
Here we will use the * selector to select all the child elements of a specified element. In the following example we have used the * selector like this: $(“div *”) which would select all the child elements of div
elements. There are two child elements of div element in the following example so the background colour of these two paras would be changed on the button click.
<!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(){ $("div *").css("background-color", "green"); }); }); </script> </head> <body> <h2>jQuery selector example to select all child elements</h2> <div> <p>This example is published on beginnersbook.com</p> <p>This is another paragraph. It contains some plain text</p> </div> <button>Click Me!</button> </body> </html>
Output:
Before the button is clicked:
After the button is clicked:
Leave a Reply