Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  90] [ 2]  / answers: 1 / hits: 24024  / 11 Years ago, tue, january 28, 2014, 12:00:00

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.


More From » html

 Answers
96

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).


[#72893] Monday, January 27, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jakobarmandr

Total Points: 363
Total Questions: 103
Total Answers: 87

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;