Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all attributes of a element based on a whitelist

Tags:

jquery

I need to remove all attributes set on certain elements (using vanilla JS or jQuery), except for a few manually selected ones. Lets say I have an image:

<img hspace="4" border="1" vspace="4" src="someimage.jpg" alt="somealt" />

and I want this as result:

<img src="someimage.jpg" alt="somealt" />

The only way I could think of is to .removeAttr() every single attribute. But the problem is that some times elements have attributes that are don't exist in the W3C specification. I want to remove all other attributes that are not whitelisted.

how would you do this?

like image 440
meo Avatar asked Sep 04 '10 17:09

meo


3 Answers

Here's a solution that iterates over the attributes list.

I'm actually only setting its value to "" (empty string), because for some reason, removeAttribute() fails when it gets to the border attribute. Investigating...

Give it a try:

var whitelist = ["src","alt"];

$('img').each(function() {
    var attributes = this.attributes;
    var i = attributes.length;
    while( i-- ) {
        var attr = attributes[i];
        if( $.inArray(attr.name,whitelist) == -1 )
            this.removeAttributeNode(attr);
    }
});​
like image 118
user113716 Avatar answered Oct 21 '22 07:10

user113716


<div id="container"><img id="img" hspace="4" border="1" vspace="4" src="someimage.jpg" alt="somealt">
</div>
<textarea rows="15" cols="80" id="dbg"></textarea>

And the javascript:

$('#dbg')[0].value += $('#container').html();
atts = $("#img")[0].attributes;
var img = $("#img"); //since it may remove id as well
for (var i = atts.length - 1; i >= 0; i--) {
    var name = atts[i].name;
    if (name != 'src' && name != 'alt') { //you can implement an array or other thing
        img.removeAttr(name);
    }
}

$('#dbg')[0].value += $('#container').html();

Try here: http://jsfiddle.net/drZhu/

like image 2
aularon Avatar answered Oct 21 '22 08:10

aularon


I generally prefer to not drop down to raw js DOM unless absolutely necessary when working with jQ so ill offer pure jQ solution:

$('img').each(function() {
    var e = $(this);
    var whitelist = ['src','title'];
    $.each(this.attributes, function(attr, value){
       if($.inArray(attr, whitelist) == -1) {
           e.removeAttr(attr);
       }
    });
});
like image 1
prodigitalson Avatar answered Oct 21 '22 08:10

prodigitalson