I want to get an array of all attributes of an HTML element (including their names and values) whose name matches a string.
<div id="myDiv" myPrefix-template="artist-group" myPrefix-records="sculptors" myPrefix-caption="People Who Sculpt"></div>
How to get an array of all the attribute-objects who's name starts with myPrefix-
?
This doesn't work:
let myDiv = document.querySelector("#myDiv");
let attribs = myDiv.attributes;
let dataAttribs = attribs.filter(attrib => {
return attrib.name.includes('myPrefix-');
});
It seems this code should work. It's based on this: https://masteringjs.io/tutorials/fundamentals/filter-array-of-objects
The following works:
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-');
});
CodePudding user response:
First, we use the document.querySelector method to select the #myDiv element from the page.
Next, we use the getAttributeNames method on the #myDiv element to get an array of all the attribute names on the element.
Then, we use the Array.prototype.filter method to filter out only the attribute names that start with data-.
Next, we use the Array.prototype.map method to get the values for the data- attributes that we filtered out in the previous step.
Finally, we use the Array.prototype.map method again to combine the attribute names and values into objects and put them in an array. This array can then be used as needed.
Here is the complete code:
let myDiv = document.querySelector("#myDiv");
let attribNames = myDiv.getAttributeNames();
let dataAttribNames = attribNames.filter(name => {
return name.startsWith('data-');
});
let dataAttribValues = dataAttribNames.map(name => {
return myDiv.getAttribute(name);
});
let dataAttribs = dataAttribNames.map((name, index) => {
return {
name: name,
value: dataAttribValues[index]
};
});
CodePudding user response:
A great answer was kindly posted by another member, but they deleted their post. Here it is:
Custom attribute names must be lower-case "myprefix-etc". .includes
won't find them in mixed-case as in the question "myPrefix-etc".
New HTML:
<div id="myDiv" myprefix-template="artist-group" myprefix-records="sculptors" myprefix-caption="People Who Sculpt"></div>
JS:
// set search-string and element
const includeString="myprefix-"
const myDiv = document.querySelector("#myDiv");
// convert attributes from NamedNodeMap to array
const attribs = [...myDiv.attributes];
// filter the array where name includes the search string
const foundAttribs = attribs.filter(attrib => {
return attrib.name.includes(includeString);
});
// print items to console
console.log(foundAttribs.map(({ name }) => name));