Attribute Starts with Selector in jQuery

In this quick post 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 my one of the friend 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 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 character ‘a’?


image from zazzle.co.uk


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, $('a[id^="a"]') code snippets will select all <a> elements having ‘id’ attribute starts with ‘a’ character.

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

jQuery Code
Meaning
id="a"
Selects all ids which has value equal to ‘a’ char.
id^="a"
Selects all ids which has value that starts with ‘a’ character.
id*="a"
Selects all ids which has value substring equal to ‘a’.
id~="a"
Selects all ids which has value equal to ‘a’ delimited by space.
id$="a"
Selects all ids which has value ending with exactly ‘a’.

Look at the output of my above code.


I hope you like it. Thanks.

Comments

Post a comment

Popular posts from this blog