javascript innerHTML adding instead of replacing
Asked Answered
D

6

33

quick question, i know we can change the content of a

<div id="whatEverId">hello one<div> by using:

document.getElementById("whatEverId").innerHTML="hello two";

now, is there a way I can ADD stuff to the div instead of replacing it??? so i can get

<div id="whatEverId">hello one hello two<div>

(using something similar of course)

Diva answered 6/7, 2011 at 9:11 Comment(0)
H
72
<div id="whatever">hello one</div>
<script>
document.getElementById("whatever").innerHTML += " hello two";
</script>
Horsepower answered 6/7, 2011 at 9:17 Comment(0)
P
9

Notice that using element.innerHTML += 'content' would empty inputs and textareas to their default, blank state, unclick checkboxes, as well as removing any events attached to those elements (such as onclick, on hover etc.) because the whole innerHTML would be reinterpreted by the browser, which means .innerHTML is emptied and filled again from scratch with the combined content.

If you need to keep the state, you'd need to create a new element (a <span> for instance) and append it to the current element, as in:

let newElement = 'span'
newElement.innerHTML = 'new text'
document.getElementById('oldElement').appendChild(newElement)
Phantom answered 15/4, 2019 at 23:53 Comment(1)
let newElement = document.createElement('span'); I think?Eloign
T
3
document.getElementById("whatEverId").innerHTML =  document.getElementById("whatEverId").innerHTML +  "hello two" + document.getElementById("whatEverId").innerHTM ;
Tow answered 6/7, 2011 at 9:15 Comment(0)
C
2

What jcomeau_ictx suggested is an inefficient way of editing the innerHTML. Check Ben cherry's PPT http://www.bcherry.net/talks/js-better-faster

The correct way will be detaching the element and making changes to it and then appending it back to the parent node. Use https://gist.github.com/cowboy/938767 Native javascript from this gist to detach element.

Colliery answered 23/2, 2014 at 21:44 Comment(1)
Please explain. First link is broken.Godiva
R
1

If you are appending, you can just change your = to a +=

document.getElementById("whatEverId").innerHTML += 'hello two';

If prefixing

document.getElementById("whatEverId").innerHTML = 'hello two' + document.getElementById("whatEverId").innerHTML;

Although I would highly recommend using jQuery or MooTools javascript libraries/frameworks to do this sort of thing. If you're adding tags not just text nodes, then you should use the DOM createElement or one of the aforementioned libraries/frameworks.

Rhoea answered 6/7, 2011 at 9:21 Comment(0)
V
1

You can do it by appending div string like this..

document.getElementById('div_id').innerHTML += 'Hello Two';

Veolaver answered 6/7, 2011 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.