Reader Level:
ARTICLE

Attribute Starts With Selector in JQuery

Posted by Abhimanyu K Vatsa Articles | JQuery May 30, 2012
In this quick article you will learn how to find elements in the DOM that have the specified attribute with a value beginning exactly with a given string.
  • 1
  • 0
  • 5321

In this quick article you will learn how to find elements in the DOM that have the specified attribute with a value beginning exactly with a given string.

Actually, this problem was asked by one of my friends, Md Ibrahim Rashid, who is from Kolkata at Kolkata Geeks Developer Conference 2012.

Let's look at the HTML Markup and a problem:

    <div>
        <a id="abc" href="#">Link 1</a><br />
        <a id="bdc" href="#">Link 2</a><br />
        <a id="acd" href="#">Link 3</a><br />
        <a id="cca" href="#">Link 4</a><br />
        <a id="adc" href="#">Link 5</a><br />
    </div>

In the above markups, I have 5 links with id attribute. If you look at the id attribute's value, you will find 3 id's value starts with char 'a'.

Now the question is, how to apply the style to the links which has id attribute starts with the character "a"?

search.jpg

Look at the jQuery code that will solve our problem.

    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <style type="text/css">
        .Class1 {
           
font: italic 20px Verdana;
        }
   
</style>
    <script type="text/javascript">
        $(document).ready(function () {
            $('a[id^="a"]').addClass("Class1");
        });
    </script>

In the above jQuery code, the $('a[id^="a"]') code snippet will select all <a> elements having an "id" attribute beginning with the character "a".

Keep in mind, jQuery uses some special characters to find the matching elements, for example:

jQuery Code

Meaning

id="a"

Seletsall ids which has value equal to 'a' char.

id^="a"

Selectsall ids which has value that starts with 'a' character.

id*="a"

Selectsall ids which has value substring equal to 'a'.

id~="a"

Selectsall ids which has value equal to 'a' delimited by space.

id$="a"

Selectsall ids which has value ending with exactly 'a'.

Look at the output of my above code.

image2.png

I hope you like it. Thanks.

COMMENT USING

Trending up