9
In a code from which I will have to add an element within a DIV. What’s the difference between first creating the element and adding it to div through the appendchild and doing DIV.insertAdjacentHTML('html correspondente ao elemento')
?
9
In a code from which I will have to add an element within a DIV. What’s the difference between first creating the element and adding it to div through the appendchild and doing DIV.insertAdjacentHTML('html correspondente ao elemento')
?
7
appendChild
inserts a html element to the gift, at the end of the list of children, so you need to create an element:
let aBlock = document.createElement('block').appendChild( document.createElement('b') );
insertAdjacentHTML
receives an html or xml string, that is, it parses an object, and place it in a specific position, which may be beforebegin
, afterbegin
, beforeend
or afterend
:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
Both examples taken from the Mozilla documentation:
In short, appendChild
adds an element at the end of the child list, insertAdjacentHTML
converts a string and inserts to a specific position.
Here an example:
document.getElementById("bt").addEventListener('click', function() {
// appendChild
let l1 = document.createElement('li');
l1.innerHTML = "appendChild";
document.getElementById("ul1").appendChild(l1);
// insertAdjacentHTML
document.getElementById('ul2').insertAdjacentHTML("afterbegin", "<li>insertAdjacentHTML</li>");
});
<span>Lista 1:</span>
<ul id="ul1">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<span>Lista 2:</span>
<ul id="ul2">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<button id="bt">Testar</button>
Browser other questions tagged javascript html dom
You are not signed in. Login or sign up in order to post.