Kwnstantinos Natsios Kwnstantinos Natsios - 2 months ago 9
HTML Question

Get all a elements inside td's from a div outside the table with Javascript

I'm currently strugling of how to get all the

A
elements inside which are inside a
td
which is inside a
table
which is inside a repeated
div
.

So this is the format of my html code

enter image description here

And i want each
a
element in a variable and below i'm going to click all these elements with a function that I have, but don't mind about that.

So I've tried this

var scrl = document.getElementsByClassName("uiScrollableAreaContent");
var circleditems = scrl[scrl.length-1].getElementsByClassName("_1pu2 _1pu4");


But it clearly doesn't get the
a
elements.
Any idea of how to do it in Javascriot (not in jquery) ??

Thanks a lot~

Answer

This should be solvable with document.querySelectorAll():

Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.


The function accepts a CSS selector. So this should give you the links you're looking for:

document.querySelectorAll(".uiScrollableAreaContent ._1pt_ table.uiGrid a._1pu2._1pu4");

A small example:

var links = document.querySelectorAll(".uiScrollableAreaContent ._1pt_ table.uiGrid a._1pu2._1pu4");
links.forEach(l => l.classList.add("highlight"));
.highlight { background-color: yellow }
<div class="uiScrollableAreaContent">
  <div class="_1pt_">
    <table class="uiGrid">
    <tbody>
      <tr><td><a href="#" class="">1</a></td></tr>
      <tr><td><a href="#" class="_1pu2 _1pu4">2</a></td></tr>
      <tr><td><a href="#" class="">3</a></td></tr>
      <tr><td><a href="#" class="_1pu2 _1pu4">4</a></td></tr>
    </tbody>
    </table>
  </div>
  <p>
    <a href="#" class="_1pu2 _1pu4">lorem ipsum</a>
  </p>
</div>