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?
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);
}
});
<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/
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);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With