jQuery
jQuery :root Selector Examples
The jQuery root selector basically selects the element that is the root of the document. So in this article, I am going to share examples on how to use it in real time. Read on to find out more.
How to use the jQuery root Selector
Let’s say we have a web page with different elements in it, such as checkbox, list items, divs, etc. We will see how the root selector works.
Example: Using the :root selector, find the root of the document and add green class to it when a button is clicked
<style type="text/css"> .existing_yellow { background-color: #FFFF99; border: 1px solid #FF0; } .existing_purple { background-color: #9999FF; border: 1px solid #90F; } .green { background-color: #D7FFD7; border: 1px solid #090; } .blue { background-color: #E1F3FF; border: 1px solid #09F; } .red_text { color: #D70000; font-weight: bold; font-style: italic; } .orange { border: 2px solid #F90; font-family: Georgia, "Times New Roman", Times, serif; } </style> <div class="divs_container"> <p> <input name="subscribe" type="checkbox" id="subscribe_0" value="Email" checked="CHECKED"> <label for="subscribe_0">Email</label> <br> <label> <input type="checkbox" name="subscribe" value="Newsletter" id="subscribe_1"> <label for="subscribe_1">Newsletter</label> <br> <label> <input type="checkbox" name="subscribe" value="RSS" id="subscribe_2"> <label for="subscribe_2">RSS</label> <br> </p> <div id="my_div1">This is MY DIV 1 <div id="my_div2" class="existing_yellow red_text green">This is MY DIV 2</div> </div> <div id="my_div3" class="existing_purple green">This is MY DIV 3</div> <div id="my_div4" class="existing_yellow">This is MY DIV 4</div> <p>This is a PARA</p> <ul id="my_list"> <li>High List item 1</li> <li>List item 2</li> <li>High List item 3</li> <li>List item 4</li> <li>High List item 5</li> </ul> </div> <p> <input type="submit" name="sbt_highlight_root" id="sbt_highlight_root" value="Add Class to Root"> </p> <script type="text/javascript" language="javascript" > $(document).ready(function(){ //Ignore this var divs_container_html = $(".divs_container").html(); //Add GREEN class to labels of the root of the document $('#sbt_highlight_root').on("click", function(e){ $(":root").addClass('green'); e.preventDefault(); }); }); </script>
When you try the above code, you will see that the GREEN class will be added to the HTML section as that is the root of the document. And hence the background color of the page will turn to green.
That’s it!
Do you know of any other ways to use the jQuery root selector? Feel free to suggest by commenting below.