最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get second element by class name if it exists - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Nov 23, 2018 at 17:11 MariaLMariaL 1,2423 gold badges18 silver badges45 bronze badges 1
  • 1 Get the node list and verify that .length is at least 2. – Pointy Commented Nov 23, 2018 at 17:12
Add a ment  | 

3 Answers 3

Reset to default 5

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].

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 }

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;
 }

})
发布评论

评论列表(0)

  1. 暂无评论