<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div> <article> <p>Lorem ipsum dolor sit amet, odio omnesque ius cu, quo ex atqui antiopam. At detracto menandri eos. Duo in causae viderer, graeci <a href="#">reprehendunt</a> has in. Decore <mark>nemore</mark> philosophia te pro, nobis legere causae ex mei, odio putant mentitum ea ius. Vix nostro deserunt explicari eu.</p> </article> </div> <ul> <li><a href="#">Link1</a></li> <li><a href="#">Link2</a></li> <li><a href="#">Link3</a></li> <li><a href="#">Link4</a></li> </ul><span></span> <a href="#">Some link</a> <script src="script.js"></script> </body> </html> 

    1 answer 1

    In your case like this:

     window.onload = function() { document.querySelectorAll('a').forEach(function(item) { if (item.closest('ul') == undefined) { console.log(item); } }); } 
     <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div> <article> <p>Lorem ipsum dolor sit amet, odio omnesque ius cu, quo ex atqui antiopam. At detracto menandri eos. Duo in causae viderer, graeci <a href="#">reprehendunt</a> has in. Decore <mark>nemore</mark> philosophia te pro, nobis legere causae ex mei, odio putant mentitum ea ius. Vix nostro deserunt explicari eu.</p> </article> </div> <ul> <li><a href="#">Link1</a></li> <li><a href="#">Link2</a></li> <li><a href="#">Link3</a></li> <li><a href="#">Link4</a></li> </ul><span></span> <a href="#">Some link</a> <script src="script.js"></script> </body> </html> 

    For browsers not knowing about closest() , the code will increase slightly:

     document.querySelectorAll('a').forEach(function(item) { let elem = item; while (elem.parentElement) { if (elem.tagName == 'UL') { break; } else { elem = elem.parentElement; } } if (elem.tagName != 'UL') { console.log(item); } }); 
    • About the browser support for this method, I think, also should be reported. - NeedHate
    • @NeedHate that's right. Completed. - UModeL