Làm sao để thay thế phần tử DOM trong JavaScript bằng một phần tử khác?
Sau đây là thuộc tính và phương thức cần thiết:
- Thuộc tính
parentNode
: trả về phần tử cha của một phần tử DOMnode.parentNode
. - Phương thức
replaceChild(newNode, oldNode)
: thay thế phần tử DOM cũoldNode
bằng phần tử DOM mớinewNode
. Trong đó,newNode
có thể là phần tử DOM đang tồn tại trêndocument
hoặc phần tử được tạo mới.
Tóm Tắt
Ví dụ 1
Ví dụ sau thay thế phần tử DOM <a>
bằng phần tử DOM mới <span>
sử dụng thuộc tính parentNode
và phương thức replaceChild()
.
Cấu trúc DOM:
index.html
<
div>
<
a id
=
"
ida"
href
=
"
#"
>
Complete JavaScript</
a>
</
div>
Code thay thế phần tử DOM:
main.js
let
aElement =
document.
querySelector
(
"#ida"
)
;
let
spanElement =
document.
createElement
(
"span"
)
;
spanElement.
innerHTML =
"Replaced Text!"
;
aElement.
parentNode.
replaceChild
(
spanElement,
aElement)
;
Ví dụ 2
Ví dụ này thay thế phần tử DOM <a>
bằng phần tử DOM mới <a>
và giữ nguyên giá trị của thuộc tính href
.
Cấu trúc DOM:
index.html
<
div>
<
a id
=
"
ida"
href
=
"
https://completejavascript.com/"
>
Complete JavaScript</
a>
</
div>
Code thay thế phần tử DOM:
main.js
let
currentA =
document.
querySelector
(
"#ida"
)
;
let
newA =
document.
createElement
(
"a"
)
;
newA.
innerHTML =
"Replaced Text!"
;
newA.
href =
currentA.
href;
currentA.
parentNode.
replaceChild
(
newA,
currentA)
;
Tham khảo: