Creating and inserting element -more deep down to DOM
There are two ways of creating and inserting element :
- HTML string :
- innerHTML ---> ADD render HTML string , not only specfic HTML content but all your content will be replaced , So any previous nodes between the tags and not just direct child , but any descendants will be entirely will be replaced with HTMl code.
- Insert adjacentHTML(position, text) ----> This avoids the extra step of serialization, making it much faster than direct
innerHTMLmanipulation. element.insertAdjacentHTML(position, text);
position- A
DOMStringrepresenting the position relative to theelement; must be one of the following strings:'beforebegin': Before theelementitself.'afterbegin': Just inside theelement, before its first child.'beforeend': Just inside theelement, after its last child.'afterend': After theelementitself.
...
Eg:
index.html
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 4</li>
<li>Item 3</li>
</ul>
</body>
index.js
const list = document.querySelector('ul')
// list.innerHTML = '<li>item 6</li>' // gets all node
unordered list be replaced by item 6
list.innerHTML = list.innerHTML + "<li>item 6</li>" //
this works because it doesn't get replaced but has Downsides
Downsides:
- all your html contain get rerendered
// use of insertadjacentHTML
<!--before begin-->
<p>
<!--after begin-->
foo
<!--before end-->
</p>
<!--after end -->
const list = document.querySelector('ul')
list.insertAdjacentHTML('afterbegin', '<li>item 0</li>')
// after element ul , but before first child
list.insertAdjacentHTML('afterend', "<div>traversed
unordered list</div>")
downsides : missing direct acess but performance wise is not
an isssue.
Comments
Post a Comment