1

Hi I have a number of elements:

<div data-stage-1="hello">Hello</div>
<div data-stage-2="hello">Hello</div>
<div data-stage-3="hello">Hello</div>

Using Javascript how would i pull these elements into an array by matching their similar data attributes? (Not the 'hello', but the 'data-stage-x')

1 Answer 1

2

You may be able to use the attributes property of the <div> element. The following is untested...

var divs = document.getElementsByTagName("div");
for (var i=0; i<divs.length; i++) {
  var d = divs[i];
  // Loop over attributes and check their names...
  for (var a=0; a<d.attributes.length; a++) {
    if (d.attributes[a].name.indexOf("data-stage-") === 0) {
       // it's a match...
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think d.attributes[a].indexOf might need to be d.attributes[a].name.indexOf, otherwise great answer.
@Colin Thanks. I was just setting up a test instance to find the correct property there. You saved me a minute or two

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.