The following process works for me, in regards to finding the correct parent. It is out of my control on the duplicated class names as shown below. But is there a shorter way to write the following in raw JavaScript?
var mvalues = document.querySelectorAll("[id*='undefinedundefined']");
mvalues.forEach((item) => {
//is there a shorter way to write this?
item.closest(".input-group").closest(".combobox-container").closest(".input-group").closest(".combobox-container").remove();
});
The html looks like this…
<div class="combobox-container">
<div class="input-group">
<div class="combobox-container">
<div class="input-group">
<span id="itemundefinedundefined"></span>
</div>
</div>
</div>
</div>
3
Answers
You could use the
:has()
selector.Keep in mind that this is relatively newer.
If you want to keep the parent column:
Assuming that
span
really is using an id and not a class, and assuming the structure of your HTML is consistent and something like this:You could write the JS shorter in this way:
or even shorter:
It just depends on what limitations you’re running into (which parts of the code you can control vs what you cannot).
If I understood correctly you want the farthest element matching the selector. jQuery offers closest, but not farthest. But it’s simple to do it on your own: get all the parents, select the last.