hidanielle
hidanielle

Reputation: 594

How to create an array of divs with a certain custom data attribute using Javascript

I have a bunch of divs on a page that have a custom data attribute of "data-type"

<div id="155544" data-type="form" data-form-id="155544">

<div data-type="question" data-question-id="119709" data-mandatory="True"></div>
<div data-type="question" data-question-id="119710" data-mandatory="True"></div>

</div>


<div id="155554" data-type="form" data-form-id="155554">

<div data-type="question" data-question-id="119711" data-mandatory="True"></div>
<div data-type="question" data-question-id="119712" data-mandatory="True"></div>

</div>

Thats basically the code, I've just taken out the actual content to avoid confusion.

I want to use Javascript to find out how many divs have the data-type of "form" in order for me to do something with them.

I have found this Hide or show all divs for a certain value of a data attribute Which is similiar to what I want to do, except I'm trying to not use jQuery.

Any solutions?

EDIT: I should also mention that I am trying to not directly use the divs "id" as those are created dynamically

Upvotes: 1

Views: 487

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

You could use querySelectorAll MDN to get a Nodelist, which you can turn into an array (and loose goodies like .namedItem()) if you want:

var divs = document.querySelectorAll('div[data-type="form"]');
var arrayOfDivs = Array.prototype.slice.apply(divs,[0]);

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382160

Without using JQuery, you might use querySelectorAll

elementList = document.querySelectorAll('div[data-type="form"]');

Demonstration (prints their number)

Upvotes: 2

Related Questions