Access the id attribute of an element selected by its class in js

2

my problem is next ... I want to access the ID attribute of an element but selecting it by its class, that is ..

this is the element.

<div class="capaClickeable" id="1"></div>

select it with getElementsByClassName because they are multiple elements

var id = document.getElementsByClassName('capaClickeable');

as it is obvious that each div has the class="capaClickeable" and a id="1" id="2" ... etc.

I want to access those ids and save them in an array or something like that. Thanks in advance.

    
asked by Odannys De La Cruz 22.09.2017 в 23:03
source

2 answers

4

You can get an array with the ids of your elements with capaClickeable class like this:

const ids = [...document.querySelectorAll('.capaClickeable')].map(el => el.id);
console.log(ids)
<div id="1" class="capaClickeable"></div>
<div id="2" class="capaClickeable"></div>
<div id="3" class="capaClickeable"></div>
    
answered by 22.09.2017 / 23:14
source
2

You do it in the following way:

Manual method

var elemento = document.getElementsByClassName('capaClickeable'); 
var id = elemento[0].getAttribute('id');

Automatic method

var elemento = document.getElementsByClassName('capaClickeable'); 
var cantidad = elemento.length;
var array_id = Array();

for(var i = 0; i < cantidad; i++){
    var id = elemento[i].getAttribute('id');

    array_id.push(id);
}

Greetings.

    
answered by 22.09.2017 в 23:06