1

Does anyone know why the following code does not work:

document.querySelector('.create-option:first-child').click()

I'm trying to get the first element with class name "create-option" and click on it.

Brown OP
  • 43
  • 7
  • 1
    _I'm trying to get the first element with class name "create-option"_ ... this is not what `:first-child` does. – Salman A Aug 26 '16 at 17:28
  • You'll need to show us the HTML that you're trying to select, otherwise we can't really tell you much about why it's not working. In the meanwhile, does it work if you use the same selector in CSS? – Spudley Aug 26 '16 at 17:28

2 Answers2

3

Just remove :first-child, it will select the first element with that class.

// just for the demo ...
[].forEach.call(document.getElementsByClassName('create-option'), function(e) {
  e.addEventListener('click', function(d) {
    alert(d.target.innerHTML);
  })
});


document.querySelector('.create-option').click();
<div class="create-option">
a
</div>
<div class="create-option">
b
</div>
<div class="create-option">
c
</div>
<div class="create-option">
d
</div>
<div class="create-option">
e
</div>
<div class="create-option">
f
</div>
<div class="create-option">
g
</div>
<div class="create-option">
h
</div>
<div class="create-option">
i
</div>
<div class="create-option">
j
</div>
<div class="create-option">
k
</div>
baao
  • 71,625
  • 17
  • 143
  • 203
0

.create-option:first-child gets the first child of the first element that is a member of that class.

To get the first element that is a member of that class, omit :first-child.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335