Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Marcos Raj
PLUS
Marcos Raj
Courses Plus Student 5,979 Points

What if I want to select a particular children from the UL?

const lis = ul.children;

In the above code it will trigger all the UL children, but what if i want to trigger only the the first children? The Code I might has been written is as mentioned below:

const lis = ul.children[0];

Kindly correct me if it is wrong. Thanks in advance!

1 Answer

Hi there Marcos!

First of all you can simply select all those children.

<ul id="list">
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
</ul>
// You can select them directly(all of them)
var li = document.querySelectorAll('#list li');
// only first
console.log('Show first element :' + li[0])
var length = li.length;
// show all
for(var i = 0; i < length; i++)
    console.log(li[i]);

Or you can use children property. Html for this case remain the same.

// selecting ul
var ul = document.querySelector('#list');
// using children property (show last element of the list)
console.log(ul.children[ul.children.length-1]);

Best regards.