Method: 1. "Element object.append (add element)" is added at the end of the interior; 2. "Element object.prepend (add element)" is added at the beginning of the interior; 3. "Element object.before( "Add element)" is added before the element; 4. "Element object.after (add element)" is added after the element.
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
1. The append
append() method inserts the specified content at the end of the selected element (still inside) .
The syntax is:
$(selector).append(content)
The example is as follows:
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").append(" <b>Hello world!</b>"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>在每个 p 元素的结尾添加内容</button> </body> </html>
Output result:
2. The prepend
prepend() method inserts the specified content at the beginning of the selected element (still inside).
The syntax is:
$(selector).prepend(content)
The example is as follows:
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").prepend("<b>Hello world!</b> "); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>在每个 p 元素的开头插入内容</button> </body> </html>
Output result:
3. before
before() method inserts the specified content before the selected element.
The syntax is:
$(selector).before(content,function(index))
The example is as follows:
</script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").before("<p>Hello world!</p>"); }); }); </script> </head> <body> <button>在P元素之前插入内容</button> <p>这是一个段落。</p> <p>这是另一个段落。</p> </body>
Output result:
4, after
after() method inserts the specified content after the selected element.
The syntax is:
$(selector).after(content,function(index))
The example is as follows:
<script> $(document).ready(function(){ $("button").click(function(){ $("p").after("<p>Hello world!</p>"); }); }); </script> </head> <body> <button>在每个P元素后插入内容</button> <p>这是一个段落。</p> <p>这是另一个段落。</p> </body>
Output result:
Related video tutorials Recommended: jQuery video tutorial
The above is the detailed content of How to dynamically add elements in jquery. For more information, please follow other related articles on the PHP Chinese website!