I have the below code to find elements with their class name:
// Get the element by their class name
var cur_columns = document.getElementsByClassName(\'colu
If you prefer not to use JQuery:
function removeElementsByClass(className){
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
You can you use a simple solution, just change the class, the HTML Collection filter is updated:
var cur_columns = document.getElementsByClassName('column');
for (i in cur_columns) {
cur_columns[i].className = '';
}
Ref: http://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html
You can use this syntax: node.parentNode
For example:
someNode = document.getElementById("someId");
someNode.parentNode.removeChild(someNode);
Brett - are you aware that getElementyByClassName support from IE 5.5 to 8 is not there according to quirksmode?. You would be better off following this pattern if you care about cross-browser compatibility:
elements[i].parentNode.removeChild(elements[i])
like the other guys said.Quick example:
var cells = document.getElementById("myTable").getElementsByTagName("td");
var len = cells.length;
for(var i = 0; i < len; i++) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
Here's a quick demo.
EDIT: Here is the fixed version, specific to your markup:
var col_wrapper = document.getElementById("columns").getElementsByTagName("div");
var elementsToRemove = [];
for (var i = 0; i < col_wrapper.length; i++) {
if (col_wrapper[i].className.toLowerCase() == "column") {
elementsToRemove.push(col_wrapper[i]);
}
}
for(var i = 0; i < elementsToRemove.length; i++) {
elementsToRemove[i].parentNode.removeChild(elementsToRemove[i]);
}
The problem was my fault; when you remove an element from the resulting array of elements, the length changes, so one element gets skipped at each iteration. The solution is to store a reference to each element in a temporary array, then subsequently loop over those, removing each one from the DOM.
Try it here.
The skipping elements bug in this (code from above)
var len = cells.length;
for(var i = 0; i < len; i++) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
can be fixed by just running the loop backwards as follows (so that the temporary array is not needed)
var len = cells.length;
for(var i = len-1; i >-1; i--) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
I prefer using forEach
over for
/while
looping. In order to use it's necessary to convert HTMLCollection
to Array
first:
Array.from(document.getElementsByClassName("post-text"))
.forEach(element => element.remove());
Pay attention, it's not necessary the most efficient way. Just much more elegant for me.