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