jQuery .add() DOM method

Syntax and Description

add method adds elements to the set of matched elements. It has three forms.

  • .add(selector[, context])
    selector: a selector to match additional elements. context (optional) is the portion of the DOM tree within which to search.
  • .add(elements)
    elements are one or more elements to add to the set of matched elements.
  • .add(html)
    html is an HTML fragment to add to the set of matched elements.

Its return value is the new jQuery object.

Add element to paragraph

The following code adds tag returned from document.getElementById.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--  w ww  . j  a  v  a 2  s. c o  m-->
           $("p").add(document.getElementById("a")).css("background", "yellow");
        });
    </script>
  </head>
  <body>
    <body>
          <p>Hello</p>
          <p id="a">Hello</p>
  </body>
</html>

Click to view the demo

Add more new tags

We can use add(anotherTag) to add more elements.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  w  ww. j av a 2s  .  co m-->
            $("div").add("p").css("background", "yellow");
        });
    </script>
  </head>
  <body>
    <body>
          <div>java2s.com</div>
          <div>java2s.com</div>
          <div>java2s.com</div>
          <div>java2s.com</div>

    </body>
</html>

Click to view the demo

Chain add method

The following code chains addClass to the result returned from an add function.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type='text/javascript'>
        var tmpExample = {
          ready : function() {<!--from w  ww  .  j av  a 2 s  .  c om-->
            $('ul#liClass1 li').add('ul#liClass3 li').addClass('justAdd');
          }
        };
        $(document).ready(tmpExample.ready);
    </script>
    <style type='text/css'>
        ul li {
            margin: 1px;
            padding: 3px;
        }
        li.justAdd {
            background: #88fac6;
        }
    </style>
  </head>
  <body id='tmpExample'>
    <ul id='liClass1'>
      <li>A</li>
      <li>B</li>
      <li>C</li>
      <li>D</li>
    </ul>
    <ul id='liClass2'>
      <li>E</li>
      <li>F</li>
      <li>G</li>
      <li>H</li>
    </ul>
    <ul id='liClass3'>
      <li>I</li>
      <li>J</li>
    </ul>
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities