Get closest ancestor by partial class with JS

Viewed 30

I need to get the closest ancestor by class, byt I need to use a partial class. For instance:

<div class="parent-1">
   <div class="child"></div>
</div>

I'd like to do somenthing like that: document.getElementsByClassName('child')[0].closest('.parent')

This would return null, since the parent's class name is parent-1. But is there a way in which I could get the parent using just the partial class name?

1 Answers

Like this

const parent = document.querySelector(".child").closest("div[class^=parent]");
console.log(parent.className)
<div class="parent-1">
   <div class="child"></div>
</div>

Related