Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending html using native javaScript

Tags:

javascript

I need to append some html to an existing element using pure javaScript:

function create(htmlStr) {
  var frag = document.createDocumentFragment(),
    temp = document.createElement('div');
  temp.innerHTML = htmlStr;
  while (temp.firstChild) {
    frag.appendChild(temp.firstChild);
  }
  return frag;
}

var target = document.querySelectorAll(".container-right");
var fragment = create(
  '<div class="freetext"><p>Some text that should be appended...</p></div>'
);
document.body.insertBefore(fragment, document.body.childNodes[0]);

It's kind of working, but I have two questions:

  1. How can I make sure that the html fragment is appended to the div with the class container-right and not just the body? Changing the last line to document.body.insertBefore(fragment, target); doesn't work.

  2. How can I insert the html after the content in the target element - after the existing content - like jQuery's append()?

Any help is much appreciated.

JsFiddle here.

like image 229
Meek Avatar asked Feb 28 '17 20:02

Meek


People also ask

How do you append to an HTML file?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')

What is append method in JavaScript?

append() method inserts a set of Node objects or string objects after the last child of the Element . String objects are inserted as equivalent Text nodes. Differences from Node.


2 Answers

var target = document.querySelector(".container-right");

var p = document.createElement('p');
p.innerHTML = "Some text that should be appended...";

var div = document.createElement('div');
div.appendChild(p);

var fragment = document.createDocumentFragment();
fragment.appendChild(div);

target.appendChild(fragment);

JSFiddle

like image 119
Paulo Pereira Avatar answered Sep 17 '22 17:09

Paulo Pereira


Try this:

var target = document.querySelector(".container-right");
target.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';
like image 39
Justin Taddei Avatar answered Sep 20 '22 17:09

Justin Taddei