2

A question: How to find out which parent contains an attribute? Example:

     <div custom-attribute>
      <div>
       <div>
        <div>
         <div><p>some text</p></div>
        </div>
       </div>
      </div>
     </div>

I can't know exactly where this attribute will be applied and on which element. I need to iterate through all the parents from the <p> element.

Without jquery

Dmitry
  • 21
  • 2

2 Answers2

3

Use a while loop to iterate the parents until you find the parent that has the attribute:

const elem = document.getElementById('elem');
let parent = elem.parentElement;

while (parent && !parent.hasAttribute('custom-attribute')) {
  parent = parent.parentElement;
}

if (parent) {
  console.log(parent);
}
<div custom-attribute>
  <div>
    <div>
      <div>
        <div>
          <p id="elem">some text</p>
        </div>
      </div>
    </div>
  </div>
</div>
Idrizi.A
  • 9,819
  • 11
  • 47
  • 88
0
const elem = document.querySelector('#elem');
const list = Array.from(document.querySelectorAll('[custom-attribute]'));
const parent = list.find(item => item.contains(elem));
// ...

If you may have not only one parent that has the custom-attribute, you'd better loop as you mentioned in question.