jQuery - SPLessons

Chapter 16

jQuery Attributes

jQuery Attributes

In jQuery, some of the most basic components are used to manipulate. When it comes to DOM element, jQuery properties or jQuery attributes assign by the element.

In jQuery, most of these attribute are available on JavaScript. See Following some common attributes.


In the following, element attributes are show…

<a href="#" target="_blank" id="a1" class="a1" title="anchor tag">This is a Anchor tag</a>

In this element tag name is a and attributes represents href, target, id, class, title each of which consists of a name and value.

jQuery easily access the attributes of elements and manipulate the attributes of elements. So that, one can easily change the properties or attributes of elements.

Attribute Selector

Atributes can be selected either using

Selecting specified attribute
$(‘[attribute]’)

Selecting specified attribute value

$(‘[attribute=”value”]’)

Eg:

$('[Title]') // Selects all elements that have title attribute
$('div[Title]') // Selects all div elements that have title attribute
$('[Title="divTitle"]') // Selects all elements that have title attribute value - divTitle
$('div[Title="divTitle"]') // Selects all div elements that have title attribute value - divTitle

Get Attribute Value

The attr() method can be used to either get value of attribute from the specified element or set a value of attributes onto all matched elements.

The attr(name) method can be used to select the value of attribute from the specified element of the document.

In below example, get the value of title attribute from p element.


<html>
<head>
   <title>jQuery First Application</title>
</head>

 <body>
   <h1>Welcome to SPLessons</h1>
   <p title="this is title of paragraph">click on this paragraph</p>
 </body>
</html>


$(document).ready(function(){
  $("p").click(function(){
     var title = $(this).attr("title");
     alert(title);
   });
});

Output:

Set Attribute Value

The attr(name, value) method can be used to set the value of name attribute from specified element of HTML document.
In below example, the value of href attribute from a tag of HTML document changed.


<html>
<head>
   <title>jQuery First Application</title>
</head>

 <body>
   <h1>Welcome to SPLessons</h1>
   <a href="#">SPLessons</a>
   <button>change href value</button>
   
   <p>Mouse over the link to see that the value of the href attribute has changed.</p>
 </body>
</html>


$(document).ready(function(){
  $("button").click(function(){
  $("a").attr("href","http://www.splessons.com");
    alert("The value of href attribute changed"); 
    
  });
});

Output:

Summary

  • The attr() method can be used to either get value of attribute from the specified element or set a value of attributes onto all matched elements.
  • The attr(name, value) method can be used to set the value of name attribute from specified element of HTML document.