Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h3>Removing:</h3> <pre><code>var div = document.getElementById('xyz'); if (div) { div.parentNode.removeChild(div); } </code></pre> <p>Or if you don't control the document and think it may be malformed:</p> <pre><code>var div = document.getElementById('xyz'); while (div) { div.parentNode.removeChild(div); div = document.getElementById('xyz'); } </code></pre> <p>(Alternatives below.)</p> <p>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. <code>id</code> values <strong>must</strong> be unique. And yet, one sees plenty of documents where they aren't.</p> <h3>Adding:</h3> <pre><code>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); </code></pre> <hr> <p>If you don't like the code duplication in my loop above and you think you need the loop, you could do:</p> <pre><code>var div; while (!!(div = document.getElementById('xyz'))) { div.parentNode.removeChild(div); } </code></pre> <p>or</p> <pre><code>var div; while (div = document.getElementById('xyz')) { div.parentNode.removeChild(div); } </code></pre> <p>...although that last may well generate lint warnings from various tools, since it <em>looks</em> like you have <code>=</code> where you mean <code>==</code> or <code>===</code> (but in this case, we really do mean <code>=</code>).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload