.add()

In this chapter you will learn:

  1. Syntax and Description for .add() DOM method
  2. How to add element to a paragraph
  3. How to add new tags
  4. How to chain add method with other methods

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><!--from   j a v  a2s  .  c o  m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
           $("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><!--from  j a v a2 s  .c o  m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("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><!--   java 2  s  .  c o  m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type='text/javascript'>
        var tmpExample = {
          ready : function() {
            $('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

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .addClass() method
  2. How to add style class for the last paragraph