his seems like something that would have a quick answer, but I can't find one. Maybe I'm searching the wrong terms? No libraries please, though I don't need cross-browser fallbacks, I'm targeting all the latest versions on this project.
I'm getting some elements:
element = document.querySelectorAll(".someselector");
YEY!
How do I delete these elements? What am I missing? Do I have to loop through them and do the element.parentNode.removeChild(element);
thing, or is there a simple function I'm missing?
Yes, you're almost right.
.querySelectorAll
returns a frozen NodeList. You need to iterate it and do things.Even if you only got one result, you would need to access it via index, like
If you only want to query for one element, use
.querySelector
instead. There you just get the node reference without the need to access with an index.Since the
NodeList
already supports theforEach
you can just useSee the NodeList.prototype.forEach(). Just bear in mind that Internet Explorer is not supported.
Edit: Internet Explorer support. If you also wish to make the above code working in IE, just add this piece of code anywhere before in your JS:
..and
NodeList
in IE will suddenly supportforEach
as well.Even more concise with Array.from and ChildNode.remove:
Ok, just saw NodeList is iterable so it can be done even shorter: