jQuery is a collection object. After finding the specified collection of elements through the $() method, a series of operations can be performed. After $(), it means that the collection object is already determined. What to do if you need to add a new element to this collection later? jQuery provides the add method for this, which is used to create a new jQuery object , the element is added to the set of matched elements. The argument to add() can accept almost any $(), including a jQuery selector expression, DOM element, or HTML fragment reference.
Let’s look at a simple case:
Operation: select all li elements, and then add the p element to the li collection
<ul>
<li>list item 1</li> <li>list item 3</li>
</ul>
<p>New p element</ p>
Process 1: Pass the selector
$('li').add('p')
Process 2: Pass the dom Element
$('li').add(document.getElementsByTagName('p')[0])
Another way is to dynamically create a P tag and add it to the collection , and then insert it into the specified position, but this changes the arrangement of the elements themselves
$('li').add('<p>New p element</p>'). appendTo(target location)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> .left { width: auto; height: 150px; } .left div { width: 150px; height: 120px; padding: 5px; margin: 5px; float: left; background: #bbffaa; border: 1px solid #ccc; } </style> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <h2>add方法()</h2> <div class="left first-div"> <div class="div"> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> <p>新的p元素</p> </div> </div> <div class="right"></div> <br/> <button>点击:add传递元素标签</button> <button>点击:add传递html结构</button> <script type="text/javascript"> $("button:first").click(function() { //把p元素添加到li的合集中 $('li').add('p').css('background', 'red') }) </script> <script type="text/javascript"> $("button:last").click(function() { //把html结构'<p>新的p元素</p>' //加入到li的合集中,为了能够在页面上显示 //需要再重新appendTo到指定的节点处 //值得注意:整个结构位置都改变了 $('li').add('<p>新的p元素</p>').appendTo($('.right')) }) </script> </body> </html>