Manipulation-DOM Replacement
一、.replaceWith()
從集合中取代指定的context。
有兩個多載方法
.replaceWith( newContent ) newContent Type: htmlString or Element or Array or jQuery
.replaceWith( Function function )
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> </head> <body> <div class="container"> <div class="inner first">Hello</div> <div class="inner second">And</div> <div class="inner third">Goodbye</div> </div> <script> $("div.second").replaceWith("<h2>New heading</h2>"); </script> </body> </html>
其結果為
<div class="container"> <div class="inner first">Hello</div> <h2>New heading</h2> <div class="inner third">Goodbye</div> </div>
二、.replaceAll()
.replaceAll( target ) target Type: Selector or jQuery or Array or Element
結果與.replaceAll()相同,只是語法對調。
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> </head> <body> <div class="container"> <div class="inner first">Hello</div> <div class="inner second">And</div> <div class="inner third">Goodbye</div> </div> <script> $("<h2>New heading</h2>").replaceAll("div.second"); </script> </body> </html>
其結果為
<div class="container"> <div class="inner first">Hello</div> <h2>New heading</h2> <div class="inner third">Goodbye</div> </div>