-1

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" class="myClass" 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-');
});
johny why
  • 2,047
  • 7
  • 27
  • 52

1 Answers1

0

A great answer was kindly posted by another member, but sadly they deleted their post. Here it is:

New HTML:

Custom attribute names must be lower-case "myprefix-etc". .includes won't find "myPrefix-etc" as stated in the question. Should be rewritten as:

<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))

References

How to convert a DOM node list to an array in Javascript?

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

johny why
  • 2,047
  • 7
  • 27
  • 52