-2

I have this code working with jQuery, but how would I get the same functionality without using jQuery?

Sk.domOutput = function(html) {
    return jQuery('body').append(html).children().last();
};

You will find the whole code : https://plnkr.co/edit/93BU7m0A5qGJlosD8QQX?p=preview

Julien
  • 1
  • 1

1 Answers1

2

Assuming html is string of HTML, you can use:

  1. Create a new HTMLElement with createElement():

    let el = document.createElement('div');`
    
  2. Then add the html inside the div by changing the innerHTML property:

    el.innerHTML = html;
    

    At this point, you have your HTML wrapped inside div tags.

  3. Append the first child of the created element to the body of the document to only append the inside of the div:

    document.querySelector('body').appendChild(el.firstChild)
    
  4. Lastly, return the newly added element:

    return el
    

So the final code is:

Sk.domOutput = function(html) {
   let el = document.createElement('div');
   el.innerHTML = html;
   document.querySelector('body').appendChild(el.firstChild)
   return el
};
Ivan
  • 34,531
  • 8
  • 55
  • 100