Reputation: 397
What is the standard DOM equivalent for JQuery
element.append("<ul><li><a href='url'></li></ul>")
?
Upvotes: 29
Views: 35051
Reputation: 3932
I think you have to extend the innerHTML property to do this
element[0].innerHTML += "<ul><li><a href='url'></a></li></ul>";
some explanation:
element
is a collection</a>
needed as some browsers only allow valid html to be set to innerHTMLHint:
As @dontdownvoteme mentioned this will of course only target the first node of the collection element
. But as is the nature of jQuery the collection could contain more entries
Upvotes: 37
Reputation: 6350
Proper and easiest way to replicate JQuery append method in pure JavaScript is with "insertAdjacentHTML"
var this_div = document.getElementById('your_element_id');
this_div.insertAdjacentHTML('beforeend','<b>Any Content</b>');
More Info - MDN insertAdjacentHTML
Upvotes: 29
Reputation: 224905
Use DOM manipulations, not HTML:
let element = document.getElementById('element');
let list = element.appendChild(document.createElement('ul'));
let item = list.appendChild(document.createElement('li'));
let link = item.appendChild(document.createElement('a'));
link.href = 'https://example.com/';
link.textContent = 'Hello, world';
<div id="element"></div>
This has the important advantage of not recreating the nodes of existing content, which would remove any event listeners attached to them, for example.
Upvotes: 12
Reputation: 150253
from the jQuery source code:
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem ); //<====
}
});
},
Note that in order to make it work you need to construct the DOM element from the string, it's being done with jQuery domManip
function.
jQuery 1.7.2 source code
Upvotes: 5