How to use JQuery attribute filters : Examples

JQuery filters make our work easy by providing a great control over selecting DOM elements.
In this post, examples for using JQuery attribute filters will be demonstrated.
Refer this post for get more details about JQuery attribute filters and their usage.

Lets see some examples of how to select elements with JQuery attribute filters.



  1. Get the elements with "class" attribute.
    $("p[class]").css("border", "3px solid red");
    This code will get the paragraph elements with "class" attribute and put a red border around it

  2. Get the elements with "id" attribute.
    $("p[id]").css("border", "3px solid red");
    This code will get the paragraph elements with "id" attribute and put a red border around it

  3. Get the elements with "id" attribute with a particular value.
    $("p[id=para1]").css("border", "3px solid red");
    This code will get the paragraph elements that has a "id" attribute with value "para1"

  4. Get the elements with "id" attribute that starts with a particular value.
    $("p[id^=para]").css("border", "3px solid red");
    This code will get the paragraph elements that has a "id" attribute and its value starts with value "para"

  5. Get the elements with "class" attribute with a particular value.
    $("p[class=para1]").css("border", "3px solid red");
    This code will get the paragraph elements that has a "class" attribute with value "para1"

  6. Get the elements with "class" attribute that starts with a particular value.
    $("p[class^=para]").css("border", "3px solid red");
    This code will get the paragraph elements that has a "class" attribute and its value starts with value "para"

  7. Get the elements with multiple attributes
    $("p[id^=para][lang*=en-]").css("border", "3px solid red");
    This code will get the paragraph elements that has a "id" attribute and its value starts with value "para" and that paragraph element should has a "lang" attribute that has "en-" string anywhere in its value
You can find the HTML code sample for practice these filters from this link and a finished version from this link.

NOTE; You should change the reference for jquery.min.js file in provided HTML sample according to your jquery directory.

No comments:

Post a Comment