I'm searching to have the closest element address-department:
<div>
<div class="field">
<input type="text" class="address-zipcode">
</div>
<div class="field">
<input type="text" class="address-department">
</div>
<div class="field">
<input type="text" class="city">
</div>
<div class="field">
<input type="text" class="country">
</div>
</div>
<div>
<div class="field">
<input type="text" class="address-zipcode">
</div>
<div class="field">
<input type="text" class="address-department">
</div>
<div class="field">
<input type="text" class="city">
</div>
<div class="field">
<input type="text" class="country">
</div>
</div>
I'm doing ajax, when i tape on zip-code then I autocomplete address-department, but now I have 2 blocks address and I want when I "input" on address-zipcode then he changes only the closest address-department.
I tried with this.closest('.field').closest('.field.address-department') but it's not working.
Do you know how I can do that ? Thank !
I agree that the naming closest is a bit confusing. you can think of closest as a reverse querySelector.
It will basicly find the next parent element that matches the statement.
so you kind of can go down but not up again with that.
I would suggest just using querySelector for this.
This would be independent of structure, order and depth.
Basicly: move back to a common base (in this case a surrounding form) and search the element.
You can find this common base by calling closest('your-base') or by accessing if via ID, or whatever.
const button = document.getElementById('button');
const button2 = document.getElementById('button2');
button.addEventListener('click', () => {
const form = document.getElementById('base');
const department = form.querySelector('.address-department');
if(!department) return;
department.classList.toggle('found');
})
button2.addEventListener('click', () => {
const form = document.getElementById('search-start');
const department = form.closest('form').querySelector('.address-department');
if(!department) return;
department.classList.toggle('found');
})
.found {
background: red;
}
<form id="base">
<div>
<div class="field">
<input type="text" class="address-zipcode" id="search-start">
</div>
<div class="field">
<input type="text" class="address-department">
</div>
<div class="field">
<input type="text" class="city">
</div>
<div class="field">
<input type="text" class="country">
</div>
</div>
<div>
<div class="field">
<input type="text" class="address-zipcode">
</div>
<div class="field">
<input type="text" class="address-department">
</div>
<div class="field">
<input type="text" class="city">
</div>
<div class="field">
<input type="text" class="country">
</div>
</div>
</form>
<button id="button">Find Department from Base</button>
<button id="button2">Find Department from Input</button>