使用纯Javascript,如何过滤目标元素中属性的所有属性和值?
下面是我尝试为我的目标实现的示例代码。但是我不知道如何获取所有属性名称,然后获取属性名称的值来过滤它。如果未列出属性名称,我想删除该属性。如果允许,我想保留仅允许的值。
[u'2017-09-10-13-45-23']
(function() {
//array allowed attr and allowed value of attr
/*
var allowedAttrValue = {};
allowedAttrValue['class'] = 'dont_remove'; // I want to use dont_remove class
allowedAttrValue['class'] = 'i_want_this_class'; // I want to use i_want_this_class class
allowedAttrValue['data-dont-remove='] = 'whatever'; //what ever value in this attribute are allowed.
// 1. I need to remove all attribute not listed
// 2. I want to filter value of allowed attribute. if value not listed I want to keep only allowed attribute (especially class; have multiple value separatedby space).
*/
var
editor = document.getElementById("post-editor"),
editorParagraph = editor.querySelectorAll("*");
for (i = 0; i < editorParagraph.length; ++i) {
elem = editorParagraph[i];
if (elem.attributes) {
//console.log(elem.attributes); //return namedNodeMap object. how to get attribute name and attribute value?
var ii;
for (ii = 0; ii < elem.attributes.length; ++ii) {
var elemAttr = elem.attributes[ii];
console.log(elemAttr); //retrun directly data-attr="haha" data-wtf="remove-me" class="hehe" and all.
}
}
}
})(); //end
答案 0 :(得分:2)
以下是使用attributes
和removeNamedItem
单击remove Me
时,它将从第一个div中删除data-remove-me
属性,因为它不在keepList中。然后你应该看到红色div变成白色..
var
keepList = {
'data-keep-me': true
};
document.querySelector('button').onclick = function () {
var divs = document.querySelectorAll('div');
for (var l = 0; l < divs.length; l ++) {
var d = divs[l];
for (var ll = d.attributes.length -1; ll >= 0; ll--) {
var a = d.attributes[ll];
if (!keepList[a.name])
d.attributes.removeNamedItem(a.name);
}
}
}
[data-remove-me] {
background-color: red;
}
[data-keep-me] {
background-color: yellow;
}
<div data-remove-me="Remove Me">
Remove Me
</div>
<div data-keep-me="Keep Me">
Keep Me
</div>
<button>Remove Them</button>
这也是你的例子,这些mods。但是您需要使用对象检查来查看更改。
注意我也以相反的顺序逐步完成属性,这是因为当你删除它们时,顺序/长度会发生变化。
(function() {
//array allowed attr and allowed value of attr
var allowedAttrValue = {
class: true,
'data-dont-remove': true
};
var
editor = document.getElementById("post-editor"),
editorParagraph = editor.querySelectorAll("*");
for (i = 0; i < editorParagraph.length; ++i) {
elem = editorParagraph[i];
if (elem.attributes) {
var ii;
for (ii = elem.attributes.length -1; ii >=0; --ii) {
var elemAttr = elem.attributes[ii];
if (!allowedAttrValue[elemAttr.name])
elem.attributes.removeNamedItem(elemAttr.name);
}
}
}
})(); //end
<div id="post-editor" class="preview">
<div data-attr="haha" data-wtf="remove me" data-xyz="">
bla bla
</div>
<div class="hehe dont_remove" data-something="haha">
bla bla
</div>
<div data-dont-remove="value" data-randomly="haha">
bla bla
</div>
<div class="this_class_not_listed i_want_this_class" data-remove-all="haha">
bla bla
</div>
<div data-data="haha">
bla bla
</div>
</div>