[Javascript]How to convert HTML string into Node



In this article, we will discuss how to convert HTML string into Nodes.




Converting HTML string to Node

This can be very simple, and you can define the function in just one line.
The following information is supplementary.

const toNode = (str) => document.createRange().createContextualFragment(str)
const elem = toNode('<p id="hoge" class="hoge">hoge</p><p>foo</p>')





DOM operations on the converted Node

The Node converted using the previous method is formally known as a DocumentFragment, which is a type of Node.
You can perform DOM operations on it just like usual.
※It seems that the getElementsByClassName method cannot be used for some reason.

const toNode = (str) => document.createRange().createContextualFragment(str)
const elem = toNode('<p id="hoge" class="hoge">hoge</p><p>foo</p>')

console.log(elem)
console.log(elem.getElementById('hoge'))
// console.log(elem.getElementsByClassName('hoge'))
console.log(elem.querySelector('#hoge'))
console.log(elem.querySelectorAll('.hoge'))
console.log(elem.children)
console.log(elem.childElementCount)
console.log(elem.firstElementChild)
console.log(elem.lastElementChild)
elem.append(toNode('<p>piyo</p>'))





The converted Node can be added to the DOM

The Node converted using the previous method can be directly added to the DOM.

const toNode = (str) => document.createRange().createContextualFragment(str)
const elem = toNode('<p id="hoge" class="hoge">hoge</p><p>foo</p>')

document.body.append(elem)






That is all, it was about how to convert HTML string into Node.

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*