• ") ? +6 java...">

    JS DOM equivalent of jQuery append

    What is the standard DOM equivalent for jQuery

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

    +6
    source share
    5 answers

    I think you need to extend the innerHTML property to do this

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

    some explanation:

    • [0] is necessary because element is a collection
    • + = extend innerHTML and don't overwrite
    • closing </a> necessary as some browsers only allow valid html for innerHTML
    +20
    source

    Use DOM manipulations, not HTML:

     var list = document.createElement('ul'); var item = document.createElement('li'); var link = document.createElement('a'); link.href = 'url'; item.appendChild(link); list.appendChild(item); element.appendChild(list); 
    +7
    source

    from jQuery source code:

     append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); //<==== } }); }, 

    Please note that for it to work, you need to build a DOM element from a string, this is done using the jQuery domManip function.

    jQuery 1.7.2 source code

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

    The easiest way to replicate the jquery append method in pure JavaScript is through "insertAdjacentHTML"

      var this_div = document.getElementById('your_element_id'); this_div.insertAdjacentHTML('beforeend','<b>Any Content</b>'); 

    More Information - MDN insertAdjacentHTML

    0
    source

    Source: https://habr.com/ru/post/914139/


    All Articles