0

I have a few different tables on the same page but unfortunately they were not assigned any unique id's. I want to remove a table using a JS command, but since id cannot be used, is it possible to delete a table based on a certain attribute it has? For example, is there a command to delete all tables on the page that have the attribute: width="25%" ?

3 Answers 3

4

You can use querySelectorAll to do that.

var x = document.querySelectorAll("table[width='25%']");
for (var i=0; i<x.length; i++) { //returns array of elements that match the attribute selector
    x[i].remove(); //call prototype method defined below
}

Removing is tricky, I found this code that makes a nice remove method

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = 0, len = this.length; i < len; i++) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

This creates a prototype remove() function that iterates the node and deletes the children.

Please note that querySelectorAll will not work in IE8 or below, but the poster of the prototype method said that it should work in IE8 but not 7.

Sign up to request clarification or add additional context in comments.

Comments

2

I know this already has some solutions, but I'll offer up one more alternative.

var tables = document.getElementsByTagName('table');
for(var i = 0; i < tables.length; i++){
    if(tables[i].getAttribute('width') == "25%"){
        tables[i].parentNode.removeChild(tables[i]);
    }
}

Demo at http://codepen.io/michaelehead/pen/HfdKx.

1 Comment

Thanks, I ended up having to use this instead, since in my case i was running the JS commands through an android webview which apparently doesnt support querySelectorAll.
0

Yes you can. The easiest way is to use JQuery. In your javascript code you would just write:

$("[attribute=value]").remove()

So in your case it could be something like $("table[width='25%']").remove()

2 Comments

Absolutely works, but he didn't ask for a jQuery answer.
Agreed. Just trying to be helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.