如何使用jquery从DOM中删除随机生成的属性?

问题描述 投票:-1回答:2

假设我知道特定元素的类名。但是,我不知道具体的属性名称,因为它是随机的,并且每个页面加载都会发生变化。

例如:

<div class="myclass" lskdjf=""></div>

在这种情况下,我想删除属性lskdjf

如果我知道属性,我可以使用这样的东西:

$('.myclass').removeAttr('lskdjf');

但是,由于我不知道属性名称,我需要另一种方法来删除它,因为我无法列出无限数量的可能字符串。

关于此属性的另一件事总是一致的:

  • 该属性始终为空(我可以在不知道属性名称的情况下删除所有空属性吗?)

如何使用jQuery从DOM中删除这些随机属性?


注意:另一种可能是剥离所有属性,然后尝试立即添加回我想要保留的属性(如类)。我不知道这是否有效,但如果可能的话,值得一试。

jquery html attributes
2个回答
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并且没有检查拼写,边缘情况等。


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>
© www.soinside.com 2019 - 2024. All rights reserved.