1. append() - 在被选元素的结尾插入内容
  2. prepend() - 在被选元素的开头插入内容
  3. after() - 在被选元素之后插入内容
  4. before() - 在被选元素之前插入内容
  5. appendTo() -向目标结尾插入匹配元素集合中的每个元素。

1 append()

image.png

  1. <p>This is paregraph</p>
  2. <button onclick="appendtext()">追加文本</button>
  3. <script>
  4. function appendtext(){
  5. var txt1 = '<br><strong>text.</strong><br>';// 以 HTML 创建新元素
  6. var txt2 = $("<i></i><br>").text("text"); // 以 jQuery 创建新元素
  7. var txt3 = document.createElement('p'); // 以 DOM 创建新元素
  8. txt3.innerHTML = "text";
  9. $("body").append(txt1,txt2,txt3); // 追加新元素
  10. }
  11. </script>

appendTo()

  1. $("button").click(function(){
  2. $("<b>Hello World!</b>").appendTo("p");
  3. });
  4. 在每个 p 元素结尾插入内容:

2 after() 和 before()

image.png

  1. <script>
  2. $(document).ready(function(){
  3. $("#btn1").click(function(){
  4. $("img").before("<b>Before</b>");
  5. });
  6. $("#btn2").click(function(){
  7. $("img").after("<i>After</i>");
  8. });
  9. });
  10. </script>

3 hasClass()

  1. 检查第一个 <p> 元素是否包含 "intro" 类:
  2. $("button").click(function(){
  3. alert($("p:first").hasClass("intro"));
  4. });

4 replaceAll()

image.png

  1. 用粗体文本替换每个段落:
  2. $(".btn1").click(function(){
  3. $("p").replaceAll("<b>Hello world!</b>");
  4. });