Phương thức HTML DOM insertAdjacentElement () chèn một phần tử tại một vị trí được chỉ định.
Cú pháp
Sau đây là cú pháp -
Gọi insertAdjacentElement () với các tham số của positionString và phần tử
node.insertAdjacentElement(“positionString”, element)
Chuỗi vị trí
Đây, “chuỗi vị trí” có thể như sau -
| positionString | Mô tả |
|---|---|
| afterbegin | Nó chèn phần tử sau phần đầu của phần tử nút |
| sau | Nó chèn phần tử sau phần tử nút |
| trước khi bắt đầu | Nó chèn phần tử trước phần tử nút |
| trước khi kết thúc | Nó chèn phần tử trước phần cuối của phần tử nút |
Ví dụ
Hãy để chúng tôi xem một ví dụ cho InsertAdjacentElement () phương pháp -
<!DOCTYPE html>
<html>
<head>
<title>insertAdjacentElement()</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertAdjacentElement( )</legend>
<h1>Family Tree</h1>
<span id="Father">Father --></span>
<span id="GrandFather">Grand Father --></span>
<span id="Myself">Myself</span>
<input type="button" onclick="rectifyTree()" value="Correct Family Tree">
</fieldset>
</form>
<script>
function rectifyTree() {
var FSpan = document.getElementById("Father");
var GFSpan = document.getElementById("GrandFather");
GFSpan.insertAdjacentElement("afterend", FSpan);
}
</script>
</body>
</html> Đầu ra
Điều này sẽ tạo ra kết quả sau -
Trước khi nhấp vào ‘Cây gia đình đúng’ nút -
Sau khi nhấp vào ‘Cây gia đình đúng’ nút -