tags:

views:

49

answers:

1

I want to remove the ChildNodes of a DIV with a specific className.

What will be the best possible way?

Thanks.

+5  A: 
var myDiv = document.getElementById('my-div'),
    children = myDiv.childNodes,
    len = children.length,
    reg = /(?:\s|^)fooClass(?:\s|$)/;

while (len--) {
     if (reg.test(children[len].className || '')) {
         myDiv.removeChild(children[len]);
     }
}
J-P
+1. But shouldn't `children[len].className.indexOf("fooClass") !== -1` suffice?
karim79
@karim79: Not in all instances. E.g. `class="myfooClass"`.
J-P
@J-P - Good point.
karim79
If there are a lot of children, then compiling the regex once and reuse it would be better...
Felix Kling
You could modify this to check for *querySelectorAll(".fooClass")*, where implemented (Firefox, Chrome, Opera, Safari, IE8+) for maximum efficiency. @Felix, @J-P.
Andy E
@J-P: I edited your already accepted answer to include the efficiency improvements suggested, hope you don't mind (feel free to rollback if you do).
Andy E
@Andy E: Hold on. Hold on. `querySelectorAll` checks for ALL descendants. AFAIK, the op only wanted direct children tested for the class... right?
J-P
@J-P: You're right, sorry about that :-) you could swap it to run `querySelectorAll("#my-div > .fooClass")` from the parent element. Or rollback, if you prefer.
Andy E
It's also a bit confusing combining the childNodes list with the staticnodelist from QSA. I'd use completely separate code paths in general. For direct children the selector should be `#my-div>.someclass`, however for this case the DOM-walking approach is so simple that I'm not sure the querySelector is actually going to be an optimisation. (`getElementsByClassName` may be faster, but again that will be for all descendants.)
bobince
Note that you are also going to get non-element nodes when you walk childNodes. You should check for `nodeType===1` before looking at `className`, otherwise you are sending `undefined` to the regex test. Which will still work as long as the class name you're checking for is not also `undefined`, but it's a bit messy.
bobince
@bobince: i've restored it to the original code. With this particular code, you wouldn't run into a situation with a live NodeList vs a static NodeList, but you're right it's probably a micro-optimisation. Also, re `className` being `undefined`, you could just use `className || ""`.
Andy E