.html() and .append() without jQuery

Spread the love

Question Description

Can anyone tell me how can I use these two functions without using jQuery?

I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.

Practice As Follows

To copy HTML from one div to another, just use the DOM.

function copyHtml(source, destination) {
  var clone = source.ownerDocument === destination.ownerDocument
      ? source.cloneNode(true)
      : destination.ownerDocument.importNode(source, true);
  while (clone.firstChild) {
    destination.appendChild(clone.firstChild);
  }
}

For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.

If you want to replace HTML, you can do it by emptying the target and then copying into it:

function replaceHtml(source, destination) {
  while (destination.firstChild) {
    destination.removeChild(destination.firstChild);
  }
  copyHtml(source, destination);
}

You may be interested in these books.

(paid link)

As an Amazon Associate I earn from qualifying purchases.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.