Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically adding/removing a div to html

I want to dynamically create a div element with id="xyz". Now before creating this, I want to remove any other div with id ="xyz" if it exists. How can i do it?

var msgContainer = document.createElement('div');
msgContainer.setAttribute('id', 'xyz');  //set id
msgContainer.setAttribute('class', 'content done'); // i want to add a class to it. it this correct?

var msg2 = document.createTextNode(msg);
msgContainer.appendChild(msg2);
document.body.appendChild(msgContainer);
}

How can i remove all divs with id =xyz if they exist before executing above code?

like image 843
jslearner Avatar asked Feb 11 '11 09:02

jslearner


1 Answers

Removing:

var div = document.getElementById('xyz');
if (div) {
    div.parentNode.removeChild(div);
}

Or if you don't control the document and think it may be malformed:

var div = document.getElementById('xyz');
while (div) {
    div.parentNode.removeChild(div);
    div = document.getElementById('xyz');
}

(Alternatives below.)

But you only need the loop with invalid HTML documents; if you control the document, there's no need, simply ensure the document is valid. id values must be unique. And yet, one sees plenty of documents where they aren't.

Adding:

var msgContainer = document.createElement('div');
msgContainer.id = 'xyz';             // No setAttribute required
msgContainer.className = 'someClass' // No setAttribute required, note it's "className" to avoid conflict with JavaScript reserved word
msgContainer.appendChild(document.createTextNode(msg));
document.body.appendChild(msgContainer);

If you don't like the code duplication in my loop above and you think you need the loop, you could do:

var div;
while (!!(div = document.getElementById('xyz'))) {
    div.parentNode.removeChild(div);
}

or

var div;
while (div = document.getElementById('xyz')) {
    div.parentNode.removeChild(div);
}

...although that last may well generate lint warnings from various tools, since it looks like you have = where you mean == or === (but in this case, we really do mean =).

like image 126
T.J. Crowder Avatar answered Oct 08 '22 08:10

T.J. Crowder