JavaScript removeChild help

I am writing a simple piece of code to draw pixels wherever the mouse is. I also want to have a clear button. Drawing works fine, but I can't get the button to work. Here are the relevant parts of my .js file:

function pixel(x, y) {
    var pix = document.createElement("div");
    pix.setAttribute("style", "position:absolute;left:" + x + "px;top:" +
        y + "px;width:3px;height:3px;background:#000;cursor:crosshair");
    return pix;
}

var mouseDown = false;

function draw(event) {
    if (!mouseDown) return;
    var x = event.clientX;
    var y = event.clientY;
    document.getElementById("box").appendChild(pixel(x, y));
}

/* Neither 1, 2, nor 3 work! */
function clear() {
    var box = document.getElementById("box");
    /* 1 */
    // box.innerHTML = "";
    /* 2 */
    // box.childNodes = new NodeList();
    /* 3 */
    for (n in box.childNodes)
        box.removeChild(n);
}

Relevant part of my HTML file:

<body onmousedown="mouseDown=true" onmouseup="mouseDown=false">
<div id="box" onmouseover="document.getElementById('box').style.cursor='crosshair'"
    onmousemove="draw(event)"></div>
<button onclick="clear()">Clear</button>
</body>

The box is also formatted a bit using CSS, but that shouldn't be a problem. I feel that the problem may be that I am removing pixels from the window, but not from the document or something else, but I have JavaScript noob, so I don’t know.

+3
source share
4 answers

Rename your function to something else (not clear ()).

function removePixels() {
var box = document.getElementById("box");

if (box.hasChildNodes() )
{
while ( box.childNodes.length >= 1 )
{
    box.removeChild( box.firstChild );       
} 
}

  }//end function
+2
source

I do not think that clearis a valid name for a function.

http://jsfiddle.net/zUJ2e/

EDIT: ,

http://www.roseindia.net/javascript/javascript-clear-method.shtml

+1

"for... in" NodeList:

for (var n = 0; n < childNodes.length; ++n)
  box.removeChild(childNodes[n]);

A NodeList , . , "for... in" - , .

, : , "" ( "" ). "style" DOM node , , , , . someElement.style.

0

, , document.clear(), clear(), .

- . , myClear(), . .

JavaScript, . JQuery, - , :

// when the document is ready...
$(document).ready(function() {
    // connect all buttons to the clear event handler.
    $('button').click(clear); 
})

JavaScript, onclick JavaScript, DOM .

<body onmousedown="mouseDown=true" onmouseup="mouseDown=false">
<div id="box" onmouseover="document.getElementById('box').style.cursor='crosshair'"
     onmousemove="draw(event)"></div>
<!-- button has an id to make it selectable with getElementById() -->
<button id="button">Clear</button>

<!-- Placed at the bottom so we have a chance of getting button -->
<script>
    document.getElementById("button").onclick = clear;
</script>

</body>
0

All Articles