使用'.包括"HTML元素属性?"



我想获得一个HTML元素的所有属性(包括它们的名称和值)的数组,其名称与字符串匹配。

<div id="myDiv" class="myClass" myPrefix-template="artist-group" myPrefix-records="sculptors" myPrefix-caption="People Who Sculpt"></div>

如何获得名称以myPrefix-开头的所有属性对象的数组?

这行不通:

let myDiv = document.querySelector("#myDiv");
let attribs = myDiv.attributes;
let dataAttribs = attribs.filter(attrib => {
return attrib.name.includes('myPrefix-');
});

看起来这段代码应该可以工作。它的基础是:https://masteringjs.io/tutorials/fundamentals/filter-array-of-objects

以下作品:

const characters = [
{ name: 'MT-caption', value: 'Some People' },
{ name: 'MT-records', value: 'sculptures' },
{ name: 'class', value: 'Deep Space Nine' }
];
tngCharacters = characters.filter(character => {
return character.name.includes('MT-');
});

另一位会员善意地发表了一个很好的回答,但遗憾的是他们删除了他们的帖子。

新HTML:

自定义属性名必须是小写的"myprefix-etc".includes找不到&;myprefix -etc&;如问题所述。应该重写为:

<div id="myDiv" class="myClass" myprefix-template="artist-group" myprefix-records="sculptors" myprefix-caption="People Who Sculpt"></div>

JS:

// get element
const myDiv = document.querySelector("#myDiv");
// convert attributes from NamedNodeMap to array
const attribs = [...myDiv.attributes];
// set search-string
const searchString="myprefix-"
// filter the array where name includes the search string
const foundAttribs = attribs.filter(attrib => {
return attrib.name.includes(searchString);
});
// print items to console
foundAttribs.forEach((attrib) => console.log(attrib.name))

引用

如何将DOM节点列表转换为Javascript中的数组?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

最新更新