简体   繁体   中英

Appending html using native 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 .

Well, I know this works:

let elem = document.querySelector ( 'css-selector (id or class)' )

That should give you your element. Then you do this:

elem.innerHTML = elem.innerHTML + myNewStuff;

That'll append your html to the innerHTML of the element. I tried it quickly, it works.

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

Based on this answer to a similar question, I have found that insertAdjacentHTML is a good fit for this kind of problems. I haven't tested it on a Node List, but with a single node it works perfectly.

insertAdjacentHTML has a great browser compatibility (back to IE4), plus it lets you decide where you want to insert the HTML (see here ).

var target = document.querySelector(".container-right");
var newContent = '<div class="freetext"><p>Some text that should be appended...</p></div>';
target.insertAdjacentHTML('beforeend', newContent);

Try this:

var target = document.querySelector(".container-right");
target.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';

Giorgio Tempesta, best answer. with this function(insertAdjacentHTML) there is no data loss if you are manipulating input fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM