jQuery API

.add()

.add( selector ) Returns: jQuery

Description: Add elements to the set of matched elements.

  • version added: 1.0.add( selector )

    selectorA string representing a selector expression to find additional elements to add to the set of matched elements.

  • version added: 1.0.add( elements )

    elementsOne or more elements to add to the set of matched elements.

  • version added: 1.0.add( html )

    htmlAn HTML fragment to add to the set of matched elements.

  • version added: 1.3.2.add( jQuery object )

    jQuery objectAn existing jQuery object to add to the set of matched elements.

  • version added: 1.4.add( selector, context )

    selectorA string representing a selector expression to find additional elements to add to the set of matched elements.

    contextThe point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

The updated set of elements can be used in a following (chained) method, or assigned to a variable for later use. For example:

$("p").add("div").addClass("widget");
var pdiv = $("p").add("div");

The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:

var pdiv = $("p");
pdiv.add("div");  // WRONG, pdiv will not change

Consider a page with a simple list and a paragraph following it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
</ul>
<p>a paragraph</p>

We can select the list items and then the paragraph by using either a selector or a reference to the DOM element itself as the .add() method's argument:

$('li').add('p').css('background-color', 'red');

Or:

$('li').add(document.getElementsByTagName('p')[0])
  .css('background-color', 'red');

The result of this call is a red background behind all four elements. Using an HTML snippet as the .add() method's argument (as in the third version), we can create additional elements on the fly and add those elements to the matched set of elements. Let's say, for example, that we want to alter the background of the list items along with a newly created paragraph:

$('li').add('<p id="new">new paragraph</p>')
  .css('background-color', 'red');

Although the new paragraph has been created and its background color changed, it still does not appear on the page. To place it on the page, we could add one of the insertion methods to the chain.

As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).

Note: To reverse the .add() you can use .not( elements | selector ) to remove elements from the jQuery results, or .end() to return to the selection before you added.

Examples:

Example: Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow.

<!DOCTYPE html>
<html>
<head>
  <style>
 div { width:60px; height:60px; margin:10px; float:left; }
 p { clear:left; font-weight:bold; font-size:16px; 
     color:blue; margin:0 10px; padding:2px; }
 </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div></div>

  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>

  <p>Added this... (notice no border)</p>
<script>

$("div").css("border", "2px solid red")
        .add("p")
        .css("background", "yellow");
</script>

</body>
</html>

Demo:

Example: Adds more elements, matched by the given expression, to the set of matched elements.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p><span>Hello Again</span>
<script>$("p").add("span").css("background", "yellow");</script>

</body>
</html>

Demo:

Example: Adds more elements, created on the fly, to the set of matched elements.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p>
<script>$("p").clone().add("<span>Again</span>").appendTo(document.body);</script>

</body>
</html>

Demo:

Example: Adds one or more Elements to the set of matched elements.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p><span id="a">Hello Again</span>
<script>$("p").add(document.getElementById("a")).css("background", "yellow");</script>

</body>
</html>

Demo:

Example: Demonstrates how to add (or push) elements to an existing collection

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p><span id="a">Hello Again</span>
<script>var collection = $("p");
// capture the new collection
collection = collection.add(document.getElementById("a"));
collection.css("background", "yellow");</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .add() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .add()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • http://www.codealpha.net Weboide

    If you are creating your own collection using code, for/while loops, etc…, do not forget to assign the mycollection.add(…) to the same variable (mycollection) again, like so:

    mycollection = $([]);
    // …some code…
    mycollection = mycollection.add(someobject);
    // …

    • Blablagum

      Yeah me too, didn't see that coming :/
      Thank you very much to post it.

      Just for info, u can know use $() instead of $([]) since 1.4. Tough, both works.

  • http://www.ciftcioglumobilya.com/kose-takimlari.htm Köşe Koltuk Takımları

    mycollection = $([]);
    // …some code…
    mycollection = mycollection.add(someobject);
    // …

  • Vks 2009

    This is very good But I have a problem

    i have append a UL inside DIV i wanna add LI inside it.

    but its not coming please giive me sample if you have added a dynamic UL dynamic ID

  • 147514112

    vcvcv

  • Knar Laquais

    This code doesn't work :
    (I want to get an element which containt a and a , for later append)
    var x = $();
    x.add($(''));
    x.add($(''));

    x doesn't have the element, only the .
    It's work when I do :
    var x = $().add($('')).add($(''));

    But I wan't to do this :
    var x = $();
    if(condition){
    x.add($(''));
    }
    x.add($(''));

    • Knar Laquais

      “containt a SPAN and a B”
      “x doesn't have the SPAN element, only the B.”

  • Gerald

    .add() is returning the given object (plus the added objects) in the order they are in the DOM, so it is *not* working like array.push().
    Just for your info, I had some great time finding that out ;)

    I tried this one on FF+FireBug, so I don't know 100% if it isn't browser specific, but i guess it is not.

    var tr = $('table').find('tr');
    var obj = $();
    var arr = [];
    for (var i = tr.length-1; i >= 0; i–) {
    obj = obj.add( tr.eq(i) );
    arr.push( tr.eq(i).get(0) );
    }
    console.log( obj );
    console.log( arr );

  • satcheorg

    $(“.rg a”).live('click',function(){
    $(“.rg a”).each(function(){
    $(this).removeClass(“this”);
    });
    $(this).addClass(“this”);
    $('.footer_archive ul').empty();
    $('.footer_archive ul').append($('#archives div#'+this.id));
    });

    is this code correct?

  • Dharmendra Singh

    Give the soulation:
    i want craet a free html element, which i can append after or before a given childelement or add forr freely in any element.

  • Dharmendra Singh

    Give the soulation:
    i want craet a free html element, which i can append after or before a given childelement or add forr freely in any element.

  • Mail Temc

    Can this also be used to add a jQuery object ? I dont see it anywhere in the documentation

    ie.

    $elements = $('div');//imagine some complicated selector;/* do lots of stuff with $elements and re-use it as a chached selector */
    
    // Question: Can we add it like this ?$('a').add( $elements ).slideUp(); // or hide() or css('color', 'red') whatever.
    
    
    • A.Lepe

      “The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.”

      Which means jQuery objects are accepted as well.

  • Prashant

    CAN”t Understand example please clear it more…please

  • http://pulse.yahoo.com/_YVUXBQGV6R35PGKJFLMCEB3U6A Michael

    Mail Temc: You *can* do what you want. I do it all the time:

    var $divs = $('div');
    var $ps = $('p');
    $div.add($p).css('background', 'yellow');

  • http://siderite.blogspot.com/ Siderite

    I have tried a query like $('.class1, .class2, .class3') and it made IE say it is too slow. I replaced with add() and it did the same. Separate queries per each class finish instantly. Using jQuery 1.4.4 on a page that has a lot of elements with those classes.

  • Aa

    mmm

  • Aa

    mmm

  • http://brad-christie.myopenid.com/ Brad Christie

    For anyone that's interested, just came across an “undocumented feature” in .add(). If you are in side an event and would like to chain another element on with the element that triggered the event, it's important to note that the selector is now working within the context of the triggered element.

    For more information, please see http://stackoverflow.com/quest…

    Also, this means if you want to reference an element that doesn't fall within the target elements tree, you need to re-specify the context. e.g.

    $('a').click(function(){
    // $(this).add('#IdOutsideOfAnchor').hide(); // won't work
    $(this).add('#IdOutsideOfAnchor',document).hide(); // will work (note context supplied)
    });

  • http://brad-christie.myopenid.com/ Brad Christie

    For anyone that's interested, just came across an “undocumented feature” in .add(). If you are in side an event and would like to chain another element on with the element that triggered the event, it's important to note that the selector is now working within the context of the triggered element.

    For more information, please see http://stackoverflow.com/quest…

    Also, this means if you want to reference an element that doesn't fall within the target elements tree, you need to re-specify the context. e.g.

    $('a').click(function(){
    // $(this).add('#IdOutsideOfAnchor').hide(); // won't work
    $(this).add('#IdOutsideOfAnchor',document).hide(); // will work (note context supplied)
    });

  • Fee

    qqd123网址之家,http://www.qqd123.com/,人们都在用的电脑主页!

  • A.Lepe

    The element's order, after using .add(), is the same order as in the DOM tree. For example:


    one
    <div>two</div>
    <label>three</label>


    $("div").add("label").add("span").each(function() {
    console.log(this.tagName);
    });

    The result will be:
    SPAN,DIV,LABEL // It is NOT: DIV,LABEL,SPAN