说我知道特定元素的类名。但是,我不知道特定的属性名称,因为它是随机的,并且每次加载页面时都会更改。
例如:
<div class="myclass" lskdjf=""></div>
在这种情况下,我想删除属性lskdjf
。
如果我知道该属性,则可以使用以下内容:
$('.myclass').removeAttr('lskdjf');
但是,由于我不知道属性名称,因此我需要另一种方法来删除它,因为我无法列出无限数量的可能字符串。
此属性只有一件事是始终一致的:
如何使用jQuery从DOM中删除这些随机属性?
注意:另一种可能是剥离所有属性,然后尝试立即重新添加我想保留的属性(例如该类)。我不知道这是否行得通,但如果可能的话,值得尝试。
答案 0 :(得分:0)
为此,不需要像jQuery这样的大库。您需要做的就是提取元素的attributes
属性,然后访问attributes[attributes.length - 1].name
并删除该属性。这是一个元素的示例,该元素添加了一个随机命名的属性,然后将其删除:
const div = document.body.appendChild(document.createElement('div'));
div.className = 'myclass';
div.setAttribute(
'rand' + Math.random().toString(36).substring(7),
'randomattributevalue'
);
console.log(div.outerHTML);
const { attributes } = div;
const attributeName = attributes[attributes.length - 1].name;
div.removeAttribute(attributeName);
console.log(div.outerHTML);
或者,使用预定义的元素:
const div = document.querySelector('.myclass');
const { attributes } = div;
const attributeName = attributes[attributes.length - 1].name;
div.removeAttribute(attributeName);
console.log(div.outerHTML);
<div class="myclass" lskdjf=""></div>
答案 1 :(得分:0)
我想你可以做这样的事情:
const element = document.getElementsByClassName('myclass')[0];
const attrs = element.attributes;
let emptyAttrs = [];
for(let i = 0; i < attrs.length; i++) {
if (attrs[i].value === "") {
emptyAttrs.push(attrs[i].name)
}
}
emptyAttrs.forEach((attributeName) => element.removeAttribute(attributeName));
这应该获取所有属性,并将带有空字符串的属性作为值存储到名为emptyAttrs
的数组中,然后遍历每个属性并将其从原始元素中删除。
注意:这可能需要调整,因为我将其直接写到了stackoverflow中,并且没有检查拼写,边缘大小写等。