Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  72] [ 5]  / answers: 1 / hits: 38886  / 14 Years ago, fri, february 11, 2011, 12:00:00

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?


More From » html

 Answers
9

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 =).


[#93783] Wednesday, February 9, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;