Remove all attributes of a element based on a whitelist
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 proble开发者_Python百科m 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);
}
});
});
Depending on the situation, you could create a new element, copy the attributes of the old one based on a whitelist, and replace; or you could transform it to a HTML string and parse it. But chances are, if you need to sanitize elements from jQuery, you are doing something wrong. What would you like to achieve?
精彩评论