Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nested DOM elements inside 'ul' element

I am looking for a way to collect all <a> tags and load then in an array using Mootool 1.1 or pure javascript.

<ul class="menu">
  <li>
    <ul>
      <li><a href="#">Group One</a>
         <ul>
           <li><a href="#">I want</a></li>
           <li><a href="#">I want too</a></li>
         </ul>
      </li>
      <li><a href="#">Group Two</a>
         <ul>
           <li"><a href="#">I want</a></li>
           <li><a href="#">I want too</a></li>
         </ul>
      </li>
     </ul>
   </li>
</ul> 

Edit Solution:

Thank you all, your responses have helped me find a more precise solution.

Mootools 1.1: @ Oskar

$$("ul.menu ul li ul li a");

@ Dimitar

document.getElements("ul.menu ul li ul li a");

Keep Geeking :)

like image 831
Q_Mlilo Avatar asked Aug 12 '10 13:08

Q_Mlilo


People also ask

How do I select a nested element?

Using the "document. querySelectorAll()" function you can select elements using CSS selectors. In CSS you select descendant (nested) elements by writing the name of an element and then a space and then another element and so on to only select elements that are found under a certain other element.

How do you grab elements from Dom?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable.

How do I identify a DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.


2 Answers

I'm not sure if you want to limit the action somehow, but getting all anchor elements in the page is easy:

var links = document.getElementsByTagName('a');

If you want to limit your search inside an element, set an id on that element so that you can easily find it, and use the getElementsByTagName on the element:

var links = document.getElementById('menu').getElementsByTagName('a');
like image 84
Guffa Avatar answered Oct 05 '22 22:10

Guffa


// for the links of the first ul.menu on the page
var menuLinks = document.getElement("ul.menu").getElements("a");
// or you can get all links children of all uls with class menu
var menuLinks = document.getElements("ul.menu a");
like image 28
Dimitar Christoff Avatar answered Oct 06 '22 00:10

Dimitar Christoff