I have a couple of input elements on a page. There are two radio
buttons and three text box
elements. I am only interested in the text box elements that are on their own line, in other words not inline. Also, not that I said text box elements, not text elements. Because I should be able to select both input[type=text]
and input[type=number]
fields.
This has to be a PURE JavaScript solution, so CSS and jQuery won't work.
Looking at the HTML, you can clearly see that the inline <input>
tags are preceeded by <label>
tags. So one idea is to find ALL input elements, transform them into an array, and search that array for items that are not preceeded by label tags.
This code doesn't work but even if it did, there should be an easier way to find this.
let selectedTextBoxes = Array.from(document.querySelectorAll('input[type=text], input[type=number]'))
.filter(i => i.previousElementSibling.tagName != 'label');
selectedTextBoxes.forEach(textBox => { textBox.classList.add('highlight') });
.highlight { background: gold; }
<h2>Select an Option</h2>
<div class="label-group">
<label>A</label>
<input type="radio"></input>
</div>
<div class="label-group">
<label>B</label>
<input type="radio"></input>
</div>
<div class="label-group">
<label>Other</label>
<input type="text"></input>
</div>
<h3>Now type in a number between 1 and 99</h3>
<input type="number"></input>
<h3>Type in a comment</h3>
<input type="text"></input>
Pure JavaScript .querySelectorAll
uses CSS selectors, which are powerful. This is the tool for the job.
In your specific case, below selects the <input>
elements that are not preceded by a <label>
element but not using that specific logic.
document.querySelectorAll("body > input").forEach(function(input){input.classList.add("highlight")});
.highlight {
background: yellow;
}
<h2>Select an Option</h2>
<div class="label-group">
<label>A</label>
<input type="radio"></input>
</div>
<div class="label-group">
<label>B</label>
<input type="radio"></input>
</div>
<div class="label-group">
<label>Other</label>
<input type="text"></input>
</div>
<h3>Now type in a number between 1 and 99</h3>
<input type="number"></input>
<h3>Type in a comment</h3>
<input type="text"></input>