Creating and inserting element -more deep down to DOM

There are two ways of creating and inserting element :

  1. 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 innerHTML manipulation.
  • element.insertAdjacentHTML(position, text);
  • position
    DOMString representing the position relative to the element; must be one of the following strings:
    • 'beforebegin': Before the element itself.
    • 'afterbegin': Just inside the element, before its first child.
    • 'beforeend': Just inside the element, after its last child.
    • 'afterend': After the element itself.
    ...



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

Popular posts from this blog

JavaScript — Double Equals vs. Triple Equals - weird things on JavaScript

06_Understanding Execution Context and Execution Stack in Javascript

Creating and inserting element- part-2