Phương thức insertAdjacentElement beforebegin trong JavaScript
Trình soạn thảo - Phương thức insertAdjacentElement beforebegin trong JavaScript
Kết quả - Phương thức insertAdjacentElement beforebegin trong JavaScript
Tự code rồi chạy thử...
Chạy Thử
<!DOCTYPE html>
<html>
<head>
<title>Phương thức insertAdjacentElement beforebegin trong JavaScript</title>
</head>
<body>
<h1 id="h1id" style="color:red">H1- Phương thức insertAdjacentElement beforebegin trong JavaScript</h1>
<p>Di chuyển một phần tử HTML lên trước một phần tử HTML khác hoặc chèn một nút phần tử lên trước một phần tử HTML khác:</p>
<div id="divid" style="color:blue">
Di chuyển thẻ này lên trước h1
</div>
<p>Click DI CHUYỂN để di chuyển dòng chữ xanh lên trước h1</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 trước thẻ h1</p>
<script>
function diChuyen() {
// Lấy phần tử div id divid
const divid = document.getElementById("divid");
// Lấy phần tử h1 id h1id
const h1id = document.getElementById("h1id");
// Di chuyển phần tử phần tử div id divid lên trước h1
h1id.insertAdjacentElement("beforebegin", divid);
}
function chenNut() {
// Lấy phần tử h1 id h1id
const h1id = document.getElementById("h1id");
// 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 trước thẻ h1
h1id.insertAdjacentElement("beforebegin", h2);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Phương thức insertAdjacentElement beforebegin trong JavaScript</title>
</head>
<body>
<h1 id="h1id" style="color:red">H1- Phương thức insertAdjacentElement beforebegin trong JavaScript</h1>
<p>Di chuyển một phần tử HTML lên trước một phần tử HTML khác hoặc chèn một nút phần tử lên trước một phần tử HTML khác:</p>
<div id="divid" style="color:blue">
Di chuyển thẻ này lên trước h1
</div>
<p>Click DI CHUYỂN để di chuyển dòng chữ xanh lên trước h1</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 trước thẻ h1</p>
<script>
function diChuyen() {
// Lấy phần tử div id divid
const divid = document.getElementById("divid");
// Lấy phần tử h1 id h1id
const h1id = document.getElementById("h1id");
// Di chuyển phần tử phần tử div id divid lên trước h1
h1id.insertAdjacentElement("beforebegin", divid);
}
function chenNut() {
// Lấy phần tử h1 id h1id
const h1id = document.getElementById("h1id");
// 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 trước thẻ h1
h1id.insertAdjacentElement("beforebegin", h2);
}
</script>
</body>
</html>
- Phương thức insertAdjacentElement beforebegin trong JavaScript nằm trong bài viết Phương thức insertAdjacentElement trong JavaScript
- ★★★★★ ★★★★★