jQuery attribute manipulation - jQuery basic tutorial 4

4. jQuery Attributes Manipulation

Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.
Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are:
  • className
  • tagName
  • id
  • href
  • title
  • rel
  • src
Consider the following HTML markup for an image element:
<img id="myImage" src="image.gif" alt="An image" 
class="someClass" title="This is an image"/>
In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value.
jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties.

Get Attribute Value:

The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements.

Example:

Following is a simple example which fetches title attribute of <em> tag and set <div id="divid"> value with the same value:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      var title = $("em").attr("title");
      $("#divid").text(title);
   });

   </script>
</head>
<body>
   <div>
      <em title="Bold and Brave">This is first paragraph.</em>
      <p id="myid">This is second paragraph.</p>
      <div id="divid"></div>
   </div>
</body>
</html>

Set Attribute Value:

The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.

Example:

Following is a simple example which set src attribute of an image tag to a correct location:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("#myimg").attr("src", "/images/jquery.jpg");
   });

   </script>
</head>
<body>
   <div>
      <img id="myimg" src="/wongpath.jpg" alt="Sample image" />
   </div>
</body>
</html>

Applying Styles:

The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.

Example:

Following is a simple example which set src attribute of an image tag to a correct location:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("em").addClass("selected");
      $("#myid").addClass("highlight");
   });

   </script>
   <style>
      .selected { color:red; }
      .highlight { background:yellow; }
  </style>
</head>
<body>
   <em title="Bold and Brave">This is first paragraph.</em>
   <p id="myid">This is second paragraph.</p>
</body>
</html>

Useful Attribute Methods:

Following table lists down few useful methods which you can use to manipulate attributes and properties:
Methods Description
attr( properties ) Set a key/value object as properties to all matched elements.
attr( key, fn ) Set a single property to a computed value, on all matched elements.
removeAttr( name ) Remove an attribute from each of the matched elements.
hasClass( class ) Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class ) Removes all or the specified class(es) from the set of matched elements.
toggleClass( class ) Adds the specified class if it is not present, removes the specified class if it is present.
html( ) Get the html contents (innerHTML) of the first matched element.
html( val ) Set the html contents of every matched element.
text( ) Get the combined text contents of all matched elements.
text( val ) Set the text contents of all matched elements.
val( ) Get the input value of the first matched element.
val( val ) Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.
Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation:
  • $("#myID").attr("custom") : This would return value of attribute custom for the first element matching with ID myID.
  • $("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value "Sample Image".
  • $("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all <input> elements to the empty string, as well as sets the title to the string Please enter a value.
  • $("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting with http:// and set its target attribute to _blank
  • $("a").removeAttr("target") : This would remove target attribute of all the links.
  • $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button.
  • $("p:last").hasClass("selected"): This return true if last <p> tag has associated classselected.
  • $("p").text(): Returns string that contains the combined text contents of all matched <p> elements.
  • $("p").text("<i>Hello World</i>"): This would set "<I>Hello World</I>" as text content of the matching <p> elements
  • $("p").html() : This returns the HTML content of the all matching paragraphs.
  • $("div").html("Hello World") : This would set the HTML content of all matching <div> to Hello World.
  • $("input:checkbox:checked").val() : Get the first value from a checked checkbox
  • $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons
  • $("button").val("Hello") : Sets the value attribute of every matched element <button>.
  • $("input").val("on") : This would check all the radio or check box button whose value is "on".
  • $("select").val("Orange") : This would select Orange option in a dropdown box with options Orange, Mango and Banana.
  • $("select").val("Orange", "Mango") : This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.

  

jQuery selectors examples - jQuery basic tutorial 3

3. jQuery Selectors

The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).
A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria.

The $() factory function:

All type of selectors available in jQuery, always start with the dollar sign and parentheses: $().
The factory function $() makes use of following three building blocks while selecting elements in a given document:
jQuery Description
Tag Name: Represents a tag name available in the DOM. For example $('p') selects all paragraphs in the document.
Tag ID: Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id.
Tag Class: Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class.
All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.
NOTE: The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $().

Example:

Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      var pars = $("p");
      for( i=0; i<pars.length; i++ ){
         alert("Found paragraph: " + pars[i].innerHTML);
      }
   });
   </script>
</head>
<body>
   <div>
      <p class="myclass">This is a paragraph.</p>
      <p id="myid">This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

How to use Selectors?

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.
Selector Description
Name Selects all elements which match with the given element Name.
#ID Selects a single element which matches with the given ID
.Class Selects all elements which match with the given Class.
Universal (*) Selects all elements available in a DOM.
Multiple Elements E, F, G Selects the combined results of all the specified selectors E, F or G.
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:
  • $('*'): This selector selects all elements in the document.
  • $("p > *"): This selector selects all elements that are children of a paragraph element.
  • $("#specialID"): This selector function gets the element with id="specialID".
  • $(".specialClass"): This selector gets all the elements that have the class of specialClass.
  • $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
  • $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
  • $("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements.
  • $("ul li:first"): This selector gets only the first <li> element of the <ul>.
  • $("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container.
  • $("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li>
  • $("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.
  • $("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>.
  • $("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>.
  • $("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass.
  • $(":empty"): Selects all elements that have no children.
  • $("p:empty"): Selects all elements matched by <p> that have no children.
  • $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
  • $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
  • $("a[@rel]"): Selects all elements matched by <a> that have a rel attribute.
  • $("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname.
  • $("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname.
  • $("a[@rel$=self]"): Selects all elements matched by <p> that have a class value ending with bar
  • $("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com.
  • $("li:even"): Selects all elements matched by <li> that have an even index value.
  • $("tr:odd"): Selects all elements matched by <tr> that have an odd index value.
  • $("li:first"): Selects the first <li> element.
  • $("li:last"): Selects the last <li> element.
  • $("li:visible"): Selects all elements matched by <li> that are visible.
  • $("li:hidden"): Selects all elements matched by <li> that are hidden.
  • $(":radio"): Selects all radio buttons in the form.
  • $(":checked"): Selects all checked boxex in the form.
  • $(":input"): Selects only form elements (input, select, textarea, button).
  • $(":text"): Selects only text elements (input[type=text]).
  • $("li:eq(2)"): Selects the third <li> element
  • $("li:eq(4)"): Selects the fifth <li> element
  • $("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
  • $("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
  • $("li:gt(1)"): Selects all elements matched by <li> after the second one.
  • $("p:gt(2)"): Selects all elements matched by <p> after the third one.
  • $("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>.
  • $("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>.
  • $("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p>
  • $("li:first-child"): Selects all elements matched by <li> that are the first child of their parent.
  • $("li:last-child"): Selects all elements matched by <li> that are the last child of their parent.
  • $(":parent"): Selects all elements that are the parent of another element, including text.
  • $("li:contains(second)"): Selects all elements matched by <li> that contain the text second.

You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element.