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:-

        <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 />

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

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;

    <script type="text/javascript">
        $(document).ready(function () {

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
Selects all ids which has value equal to ‘a’ char.
Selects all ids which has value that starts with ‘a’ character.
Selects all ids which has value substring equal to ‘a’.
Selects all ids which has value equal to ‘a’ delimited by space.
Selects all ids which has value ending with exactly ‘a’.

Look at the output of my above code.

I hope you like it. Thanks.


Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples