I have two divs with same class names with one input inside each. First one has id, second - no, I need get closest input to my input with id. I can't set an id to second input, or change class names of divs.
HTML -
<div >
<input id="myInput"/>
</div>
<div >
<input/> <-- which I need to get ->
</div>
I have tried to use something like below, but, this operation returns me the first input.
$("#myInput").closest("input")
CodePudding user response:
So you need to pick parent the "picker" and then you need to pick the next "picker" and then find the input.
const inp = $("#myInput").closest('.picker').next('.picker').find('input');
inp.val('found it');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<input id="myInput" />
</div>
<div >
<input/>
<-- which I need to get ->
</div>
CodePudding user response:
Simpler Alternative
There is a much simpler solution than the selected answer that uses a single css selector to return the targeted input.
const selector = ".picker:has(input[id]) ~ .picker input:not([id])";
$(selector) // jQuery
document.querySelector(selector) // native JavaScript
How the selector works
.picker:has(input[id])
selects the picker that contains an input with an id.
~ .picker input:not([id])
selects the next picker input without an id.
Note that the :has() selector always works with jQuery, but it might not work with native JavaScript/css (see: browser compatibility). Also see subsequent-sibling combinator for how the tilde works.
Snippet
The snippet shows how we can find the targeted input even when nested in other elements.
const selector = ".picker:has(input[id]) ~ .picker input:not([id])";
console.log("jQuery:", $(selector)[0]);
try {
console.log("Native:", document.querySelector(selector));
}
catch(error) {
console.error("Native: Your browser does not support the :has() selector.");
}
<div ><input/></div>
<div></div>
<div ><div></div><div><input id="myInput"/></div></div>
<div></div>
<div ><input data-tag="correct" /></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>