Overview on JQuery Selectors
A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria.The $() factory function:
The factory function $() makes use of following three building blocks while selecting elements in a given document:Selectors are the key that make jQuery useful. You start by selecting content and then applying a jQuery function to it
We can select Elements in the following ways
- Using Tag Name:
- $('p').css("border", "solid 1px
red");
- $('p').css("border", "solid 1px
- Using Tag ID
- $('#Some-Id').css("border", "solid 1px red");
- Using Tag Class
- $('.Some-Class').css("border", "solid 1px red");
- Using Universal (*)
- $('*').css("border", "solid 1px
red");-------- Selects all the elements - $("p > *").css("border", "solid 1px
red"); ------ selects all the elements that are children of paragraph
element.
- $('*').css("border", "solid 1px
- Multiple elements selecting
- $("code, em, strong").css("border", "solid 1px red"); ------ Selects all the
elements that are matched with <code> <em> <strong>.
- $("code, em, strong").css("border", "solid 1px red"); ------ Selects all the
Example on selectors
This is example changes the color of the particular tageed data dynamically. Here you can enter the Tag Name or Tag ID or Tag Class or MultipleJust Copy the below Html elements into your html page (Do forget to include JQuery library file in your header tag Other see here to know how to include).
<div id="selectors"> <ul> <li>Selector: <input type="text" id="selector" value="div"/> <input type="button" id="btn" value="Run"/></li> </ul> <pre class="stocky"><div id="body"><span><div id="body"></span> <h2><span><h2>Some Header</h2></span></h2> <div class="contents"><span><div class="contents"></span> <p><span><p></span>Paragraph 1<span></p></span></p> <p><span><p></span>Paragraph 2<span></p></span></p> <span></div></span></div> <span></div></span></div> </pre> <div class="sample" style="float:left;"> <div ID="body" style="float:left;"> <h2>Heading</h2> <div class="contents" style="float:left;"> <p>Paragraph content</p> <p>Paragraph content</p> </div> </div> </div> </div>
This is the Script you need to include after the above.
<script type="text/javascript"> $("#btn").click(function() { var selector = $("#selector").val(); $("#selectors pre, #selectors div.sample") .find("*").removeClass("found").end() .find(selector).addClass("found"); return false; }); </script>
The Out puts will be like the following based on the selected item
Post a Comment