Lumnezia
Lumnezia

Reputation: 796

Javascript - Select first element of child of child of element

I have the following HTML:

<div class="list">
<div class="items">
    <ul>
        <li>IMPORTANT</li>
        <li>...</li>
        <li>...</li>
        <li>...</li>
        <li>...</li>
        <li>...</li>
    </ul>
    <ul>
        ...
    </ul>
</div>

Now I want to select the First "li" in the first "ul" in the div "items" in the div "list" via Javascript.

Upvotes: 5

Views: 29800

Answers (5)

dtech
dtech

Reputation: 14069

You can use any combination of getElementById, getElementsByClassName and getElementsByTagName.

var divs = document.getElementsByClassName('items');
var uls = divs[0].getElementsByTagName('ul');
var lis = uls[0].getElementsByTagName('li');
var li = lis[0];
//// li is now the first list element of the first list inside the first div with the class "items"

It is easier if you give some elements an id, then you can use an getElementById instead of the clunky getElements_ and don't have to deal with arrays:

var div = document.getElementById('items');  // If the right <div> has an id="items"
var uls = div.getElementsByTagName('ul');
var lis = uls[0].getElementsByTagName('li'); // Or instead of uls[0] give the right ul and id
var li = lis[0];                             // Or instead of lis[0] give the right li and id

The easiest solution is probably to use a library like jQuery, in which you can do this with selectors:

var li = $('div.items:first ul:first li:first');

edit: I'd recommend David Thomas's solution if you can't use jQuery and have no problem with excluding older browsers (mainly IE7 or lower).

Upvotes: 10

Siva Charan
Siva Charan

Reputation: 18064

Using JQuery, it's more easy to target

$(".list .items ul:first li:first")

OR

$("div.list div.items ul li").first()

Refer LIVE DEMO

Upvotes: 0

David Thomas
David Thomas

Reputation: 253506

If you're targeting modern browsers, I'd suggest:

var importantLi = document.querySelector('.list .items li');

References:

Upvotes: 8

Alexander
Alexander

Reputation: 20244

your div would normally be <div id="items"> or <div id="items" class="items"> since a div with id is unique on a page.

Then

firstLi = document.getElementById("items").firstChild.firstChild;

Upvotes: 2

mrakodol
mrakodol

Reputation: 1243

you can try this <script>$('.items ul li:first').val()</script>

Upvotes: -2

Related Questions