简体   繁体   中英

Changing content in a div with JS without destroying its content

I am using an application where on change in the select box value my javascript function would be called. In the function I have an if/else statement. If the condition validates, it displays me a graph in my div , else it displays text in the same div .

var arrayDataSource = [];
//for example this array has the following [[1,0.2],[2,0],[3,1]
$.each(test, function(index, value) 
{
    //code to load data to that array
});
)
if(arrayDataSource.length > 0) {
    //draw graph
} else {
    document.getElementById('mydiv').innerHTML = "some text";
}

When I try to run the else condition my content gets overwritten as I am using an innerHTML to display text.

Do I have any other options to display text with javascript without using innerHTML ? I have also seen some DOM functions and other relevant posts but nothing worked for me. My div properties should remain as they are even after the else condition.

Use insertAdjacentHTML instead of innerHTML as it does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element.

document.getElementById('overAllContainer').insertAdjacentHTML('beforeend', 'some text');

A better way to do it would be to append a new element with an attribute such as a class or an id to your overAllContainer in order to easily remove it when your selection changes. You can do it via

document.getElementById('overAllContainer').insertAdjacentHTML('beforeend', '<p class="message">some text</p>');

Or via

var message = document.createElement('p');
message.setAttribute('class', 'message');
message.innerText = 'some text';
document.getElementById('overAllContainer').appendChild(message);

And then when you want to remove the message based on the selection changing,

document.querySelector('#overAllContainer .message').remove();

Changing content in a div with JS without destroying its content you can simply use +=; instead of = only.

The code will be document.getElementById('overAllContainer').innerHTML += "some text";

Use document.createTextNode :

var text = document.createTextNode("some text");
document.getElementById('mydiv').appendChild(text);

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