Phương thức insertAdjacentElement beforeend trong JavaScript

Phương thức insertAdjacentElement beforeend trong JavaScript

Phương thức insertAdjacentElement beforeend trong JavaScript

Tự code rồi chạy thử... Chạy Thử
<!DOCTYPE html>
<html>
<head>
<title>Phương thức insertAdjacentElement beforeend trong JavaScript</title>
</head>
<body>

<h1>Phương thức insertAdjacentElement beforeend trong JavaScript</h1>

<p>Di chuyển một phần tử HTML ra sau các phần tử con của một phần tử HTML khác hoặc chèn một nút phần tử ra sau các phần tử con của một phần tử HTML khác:</p>

<div id="divid" style="border:1px solid #ddd; padding:10px">
    <p>Thẻ p 1</p>
    <p>Thẻ p 2</p>
    <p>Thẻ p 3</p>
</div>
<p id="pchen" style="color:blue">Chèn thẻ này ra sau các phần tử con khung thẻ p</p>
<p>Click DI CHUYỂN để di chuyển dòng chữ màu xanh ra sau các phần tử con khung thẻ p</p>
<button onclick="diChuyen()">DI CHUYỂN</button>
<button onclick="chenNut()">CHÈN NÚT</button>
<p>Click CHÈN NÚT để chèn nút phần tử h2 mới tạo sau các phần tử con khung thẻ p</p>
<script>
function diChuyen() {
  // Lấy phần tử div id divid
  const divid = document.getElementById("divid");
  // Lấy phần tử p id pchen
  const pchen = document.getElementById("pchen");
  // Di chuyển phần tử pchen ra sau các phần tử con của thẻ div có id divid
  divid.insertAdjacentElement("beforeend", pchen);
}
function chenNut() {
   // Lấy phần tử div id divid	
  const divid = document.getElementById("divid");
  // Tạo nút phần tử h2
  const h2 = document.createElement('h2');
  h2.textContent = 'Thẻ h2';
  // Chèn nút phần tử h2 ra sau các phần tử con của thẻ div có id divid
  divid.insertAdjacentElement("beforeend", h2);
}
</script>
</body>
</html>
Phương thức insertAdjacentElement beforeend trong JavaScript nằm trong bài viết Phương thức insertAdjacentElement trong JavaScript