开发者

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 msgCont开发者_开发百科ainer = 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜