admin管理员组

文章数量:1298119

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?

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?

Share Improve this question edited Feb 11, 2011 at 9:20 T.J. Crowder 1.1m199 gold badges2k silver badges1.9k bronze badges asked Feb 11, 2011 at 9:13 jslearnerjslearner 22.1k18 gold badges38 silver badges35 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 23

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

本文标签: javascriptdynamically addingremoving a div to htmlStack Overflow