Is there a way to locate the preceding element of a specific type, whether it belongs to the same parent or not?
For instance, I am interested in identifying the prior input[type="text"]
element and giving it focus.
Currently, I can target the previous sibling within the same parent, but I would like to refine that to exclusively select input[type="text"]
elements and extend it to encompass the previous parent as well.
The answer that follows should utilize vanilla JavaScript exclusively.
document.addEventListener('keydown', function(e) {
// if backspace is pressed and the input is empty
if (e.keyCode === 8 && e.target.value.length === 0) {
// This will set focus to the previous input element
e.target.previousSibling.previousSibling.focus();
}
}, false);
<div>
<input type="text">
<input type="text">
</div>
<div>
<input type="text>
<input type="text">
</div>
<div>
<input type="text">
<input type="text">
</div>