With querySelectorAll():
- Logical AND (&&) can be archived by specifying elements and attributes without commas.
- Logical OR (||) can be archived by specifying elements and attributes with commas.
For example, there is 2 forms as shown below:
<form class="form1" method="post">
<input type="text" id="input1" name="fruits" value="Apple">
<p id="p1">Orange</p>
</form>
<form class="form2" method="post">
<input type="text" id="input2" name="fruits" value="Banana">
<p id="p2">Kiwi</p>
</form>
<Logical AND (&&)>
Then, you can select Apple's <input>
and Banana's <input>
with [name="fruits"]
as shown below:
document.querySelectorAll('[name="fruits"]');
// Apple's <input> and Banana's <input>
Now by specifying elements and attributes without commas, you can select only Apple's <input>
as shown below:
// ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
document.querySelectorAll('form.form1 input[name="fruits"][id="input1"]');
// Apple's <input>
In addition, you can replace .form1
with [class="form1"]
and [id="input1"]
with #input1
as shown below:
// .form1 [id="input1"]
// ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
document.querySelectorAll('form[class="form1"] input[name="fruits"]#input1');
// Apple's <input>
<Logical OR (||)>
Next, you can select Apple's <input>
with #input1
as shown below:
document.querySelectorAll('#input1');
// Apple's <input>
Now by specifying elements and attributes with commas, you can select Apple's <input>
, Orange's <p>
, Banana's <input>
and Kiwi's <p>
as shown below:
// ↓ ↓ ↓ ↓ ↓
document.querySelectorAll('#input1, #input2, p');
// ↑ ↑
// Apple's <input>, Orange's <p>, Banana's <input> and Kiwi's <p>
<Logical AND (&&)> and <Logical OR (||)>
In addition, of course, you can use both Logical AND and Logical OR together as shown below:
document.querySelectorAll('input#input1, input#input2, p#p1')[
// Apple's <input>, Orange's <p> and Banana's <input>