jQuery Attributes Selector

In a jQuery some of the most important components we are using in DOM element are the properties or attributes assign by the element.

jQuery some most attribute are available on JavaScript. Following some common attributes.

  • tag name
  • class name
  • id
  • href
  • src
  • rel

following one element with represent attributes on that element. This element tag name is p, and attributes is represent id, class, title consists of some value.

<p id="div1" class="div1" title="First Paragraph">Paragraph</p>

Get Attribute Value

This example introduce to the attr() method. it used to get value of an attribute from the first element in the matched attributes.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery attr() function</title>
  <script src="jquery-latest.min.js"></script>
  <script>
    $(document).ready(function() {
      var title = $("p").attr("style");
      $("#div1").text(title);
    });
  </script>
</head>
<body>
  <div>
    <p style="background-color:#FF9933; font-family: Arial, sans-serif; text-align: center;">First paragraph start here...</p>
    <div id="div1">Attribute values come from above paragraph</div>
  </div>
</body>
</html>

Run it...   »

Understand above example

  • Declare Variable for example var title
  • Assign value to the variable from the style attribute of <p> element. For example. $("p").attr("style");
  • Set text to the variable value on selector element for example $("#div1").text(title);
  • <div> element having attribute id="div1" will show text of previous set text.