03 – Selecting elements using attributes in jQuery

Attribute selectors allow you to select elements based on their attributes. Let’s take a look at the ul part of our page.

<ul class="list-one">
			<a href="http://dan.saigon.ro">My website contains:</a>
				<li><a href="http://dan.saigon.ro/about/">About Page</a></li>
				<li><a href="http://dan.saigon.ro/portfolio/">Portfolio Page</a></li>
				<li><a href="http://dan.saigon.ro/contact/">Contact Page</a></li>
				<li>And many other pages</li>
		<li>I have other websites as well
				<li>About chemistry website</li>
				<li>About Math website</li>

Notice the http:// at the beginning of the string value for the link’s href attribute. In CSS , you could select links that have an href value starting with http:// with the following selector:


In jQuery we can do it as shown below:

var $linksToWeb = $("a[href^='http://']");

The above code matches all links with an href value beginning with the http://. The ^ character specifies that the match has to be at the beginning of a value (see the similarity with regular expressions in Python and many other programming languages).

Pay attention to the single and double quotes!

Let’s say you want all the links but those pointing to Dan’s website homepage.

$(" a[href!='http://dan.saigon.ro'] ")

The “not equal attribute” selector selects all links but not the one shown in code.

Here you have another examples:

  • form[method] – This matches any form element that has a method attribute.
  • div[title^='main'] – This selects all div elements with a title attribute whose value begins with main.
  • a[href$='.jpg'] – This selects all links that reference a JPG files. The $ sign means that it has to match at the end.
  • a[href*='dan.saigon.ro'] – This selector matches all a elements that reference the Dan’s website.
  • div[class|='main'] – This selector will select all the div-s that have the class="main" or a class name that starts with main.
  • span[moto-brands~="honda"] – This selects span-s elements that have an attribute like moto-brands="honda" but also moto-brands="honda yamaha suzuki".
  • input[type="text"][required] – This selector retrieves all the input-s that are required and are of type text.

Leave a Reply