MariaL
MariaL

Reputation: 1242

get second element by class name if it exists

I'm trying to get the ID of an element by class name like this

var prod_id2 = document.getElementsByClassName('select-selected')[1].id
document.getElementById('hidden-input-2').value = prod_id2;

This works fine, but my issue is that if there's only one element with that class it breaks the functionality, so I need some sort of if statement to only define this var if there is a second div with that class. Any ideas?

Upvotes: 3

Views: 4554

Answers (3)

Dmitriy
Dmitriy

Reputation: 1241

It breaks the functionality I think because you are grabbing the 2nd element specifically. You can do:

const prod_id2 = document.querySelectorAll('.select-selected');

and loop over the elements and grab the ID

prod_id2.forEach((prod, index) => {
 if(index === 2) {
  document.getElementById('hidden-input-2').value = prod.id;
 }

})

Upvotes: 0

Gutelaunetyp
Gutelaunetyp

Reputation: 1882

Here is how to check for the second element.

You can also set another fallback , different to null:

document.addEventListener("DOMContentLoaded", function(event) {
  var selectedElements = document.querySelectorAll('.selected-selected'),
    prod_id2 = selectedElements[1] || null;
  alert(prod_id2)
});
<div id="test" class="selected-selected"></div>

You can also check that value then:

if (prod_id2) { // do some other stuff with the set value }

Upvotes: 0

Willem van der Veen
Willem van der Veen

Reputation: 36650

Try this:

const elements = document.querySelectorAll('.test');

if (elements[1]) {
  elements[1].innerText = 'Hithere';
}
<div class="test">hi</div>
<div class="test">hi</div>
<div class="test">hi</div>

  1. document.querySelectorAll('.test'); selects all elements with the class test and returns a nodelist.
  2. Then we can access the second element via of the nodelist with elements[1].

Upvotes: 5

Related Questions