Home > Article > Web Front-end > How to replace dom elements with jquery
Method: 1. Use the replaceWith() method, which is used for all matching elements in the collection. The syntax is "element object.replaceWith(content, function(index))"; 2. Use replaceAll() Method, which is used to replace selected elements with new HTML elements. The syntax is "element object.replaceAll(selector)".
The operating environment of this tutorial: windows10 system, jquery3.6.0 version, Dell G3 computer.
1. replaceWith() method
$(selector).replaceWith(content,function(index))
content is required. Specifies the content to be inserted (can include HTML tags).
Possible values:
HTML element
jQuery object
DOM element
#function(index) Optional. Specifies a function that returns replacement content.
index - Returns the index position of the element in the collection.
$(DOM).replaceWith(newContent) is used to replace all matching elements in the collection and return the deleted element collection:
<!DOCTYPE html> <html> <head> <title></title> <script src="jquery.js"></script> <script type="text/javascript"> $('document').ready(function (){ $('body>input').click(function (){ $('body>ul>li:gt(1)').replaceWith('<li>替换后的元素</li>') }) }) </script> </head> <body> <input type="button" value="替换"> <ul> <li>第一个</li> <li>第二个</li> <li>第三个</li> <li>第四个</li> </ul> </body> </html>
Output result:
2. replaceAll() method
$(newContent).replaceAll(DOM) has the same function as $(DOM).replaceWith(newContent), only But the parameter position is changed (you can directly assign the style later):
<!DOCTYPE html> <html> <head> <title></title> <script src="jquery.js"></script> <script type="text/javascript"> $('document').ready(function (){ $('body>input').click(function (){ $('<li>替换后的元素</li>').replaceAll('body>ul>li:gt(1)').css('color','orange'); }) }) </script> </head> <body> <input type="button" value="替换"> <ul> <li>第一个</li> <li>第二个</li> <li>第三个</li> <li>第四个</li> </ul> </body> </html>
Output result:
Video tutorial recommendation: jQuery video Tutorial
The above is the detailed content of How to replace dom elements with jquery. For more information, please follow other related articles on the PHP Chinese website!