- Jquery provides element selector using attribute condition.This is very handy for developers for element selection from document.
- In this Demo, “we will see a how these attributes selector can be used for DOM element selection”.
- List of these attribute selector are as below,
[<attributename>]
Find All element having a attribute named <attributename>.
[<attributename> = <“value”>]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
[<attributename> |= <“value”>]
Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).
[<attributename> != <“value”>]
Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value.
[<attributename> *= <“value”>]
Selects elements that have the specified attribute with a value containing the a given substring.
[<attributename> $= <“value”>]
Selects elements that have the specified attribute with a value ending exactly with a given string.
[<attributename> ~= <“value”>]
Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.
[<attributename> ^= <“value”>]
Selects elements that have the specified attribute with a value beginning exactly with a given string.
- The HTML markup has following elements in dom,
<span title='student'>sandeep kumar patel</span>
<span title='top-fruit'>Apple</span>
<span title='fruit'>Bananana</span>
<span title='fruit'>Mango</span>
<span title='seasonal fruit market item'>Orange</span>
<span title='flower'>Rose</span>
<span title='flower'>Lotus</span>
<span title='domestic-animal'>cow</span>
<span>CocaCola</span>
- The jquery methods for element selections are as below,
/*Finds all span elementss with a title attribute.*/
$("span[title]").css("background", "grey");
/*Finds all span elements with a title attribute that is fruit.*/
$("span[title|='top']").css("color", "red");
/*Finds all span elements with a title attribute value containing the a given substring*/
$("span[title*='lo']").css("color", "orange");
/*Finds all span elements with a title attribute value beginning exactly with a given string.*/
$("span[title^='market']").css("border-bottom", "5px solid green");
/*Finds all span elements with a title attribute value containing a given word, delimited by spaces.*/
$("span[title~='fruit']").css("font-size", "30px");
/*Finds all span elements with a title attribute ending exactly with a given string.*/
$("span[title$='animal']").css("background", "yellow");
/*Finds all span elements without a title attribute having value*/
$("span[title!='fruit']").css("border-bottom","2px solid blue");
- The JS Fiddle link is as below
- The result will render in the browser as below screen shot,