Battery
Battery

Reputation: 397

JS DOM equivalent for JQuery append

What is the standard DOM equivalent for JQuery

element.append("<ul><li><a href='url'></li></ul>")?

Upvotes: 29

Views: 35051

Answers (5)

Tom
Tom

Reputation: 4180

element.innerHTML += "<ul><li><a href='url'/></li></ul>";

Upvotes: 0

Tobias Krogh
Tobias Krogh

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:

  • [0] needed because element is a collection
  • += extend the innerHTML and do not overwrite
  • closing </a> needed as some browsers only allow valid html to be set to innerHTML

Hint: 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

M_R_K
M_R_K

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

Ry-
Ry-

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

gdoron
gdoron

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

Related Questions