1

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 Answer 1

3

Like this

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.