1

Is there anyway I can get an input by its class name? For example I have this html code below:

<span class="inputClass">
   <input type="checkbox"/>
<span>

I would like to see if that input is selected using its class name. There is no option I can give it an ID because we do not have access to this source code.

Zeusox
  • 7,708
  • 10
  • 31
  • 60

2 Answers2

2

use document.querySelector('.inputClass > input[type="checkbox"]').

const inputEle = document.querySelector('.inputClass > input');
console.log('isChecked: ', inputEle.checked);

inputEle.addEventListener('change', function() {
    console.log(this.checked);
});
<span class="inputClass">
    <input type="checkbox"/>
<span>
random
  • 7,756
  • 3
  • 19
  • 25
1

You can select the input from the children of the parent class

.inputClass > input[type=checkbox]

Below is working snippet.

console.log(document.querySelector('.inputClass > input[type=checkbox]').checked)
<span class="inputClass">
   <input type="checkbox"/>
<span>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73