开发者

how to append to a object with innerHTML

开发者 https://www.devze.com 2022-12-09 05:33 出处:网络
Is there a way to add information to a DOM object with .innerHTML without replacing what exists there?

Is there a way to add information to a DOM object with .innerHTML without replacing what exists there?

For example: document.getElementById('div').innerHTML = 'stuff';

Would return <div id="div">stuff</div>

And then a similar call: document.getElementById('div').inn开发者_高级运维erHTML = ' and things';

Would set the div to <div id="div">stuff and things</div>


document.getElementById('mydiv').innerHTML = 'stuff'
document.getElementById('mydiv').innerHTML += 'and things'
document.getElementById('mydiv').innerHTML += 'and even more'


You could use Element.insertAdjacentHTML().

insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation.

If you want to append your stuff at the end of this Element, you would do

const div = document.getElementById("div");
div.insertAdjacentHTML('beforeend', 'stuff');;


The += operator.


why not try

document.getElementById('div').innerHTML += ' and things';

note the "+"


There are mistakes in your examples. But you could just do this:

var myDiv = document.getElementById('div');

myDiv.innerHTML = myDiv.innerHTML + ' and things';


change it to this:

document.getElementById.innerHTML('div') = 
    document.getElementById.innerHTML('div') + ' and things';

the ol' x = x+1 style of concatenation.

though I don't think "document.getElementById.innerHTML('div')" is even proper syntax? Don't you mean "document.getElementById('divid').innerHTML"?


Maybe:

document.getElementById('div').innerHTML = document.getElementById('div').innerHTML + ' and things'
0

精彩评论

暂无评论...
验证码 换一张
取 消