Get the first <li> WITHOUT jQuery

It may have been asked, but scrolling around 40 search results only shows the jQuery solution. Let's say I want to get the first element in an unordered list and apply a new text color to it, and it is one. It is simple with jQuery.

Markup →

<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> 

With jQuery →

 $("ul > li:first").css("color", "blue"); 

Question: how can I achieve this without jQuery?


SOLUTION: I found this method to work in all browsers (with IE7 +) →

 document .getElementsByTagName("ul")[0] .getElementsByTagName("li")[0] .style.color = "blue"; 
+4
source share
6 answers

You can use querySelector (IE7 and below is not supported):

 document.querySelector("ul > li") 

Or querySelectorAll :

 document.querySelectorAll("ul > li")[0] 

Or getElementsByTagName :

 document.getElementsByTagName("ul")[0] .getElementsByTagName("li")[0] 

The best way to change the IMO style is to set the class. You do this by setting (or extending) the .className property of the resulting element.

Otherwise, you can set individual styles using the .style property.


Update

As @Randy Hall noted, perhaps you need li all ul elements first. In this case, I would use querySelectorAll as follows:

 document.querySelectorAll("ul > li:first-child") 

Then repeat the result to set the style.


To use getElementsByTagName , you can do this:

 var uls = document.getElementsByTagName("ul"); var lis = [].map.call(uls, function(ul) { return ul.children[0]; }); 

You will need the Array.prototype.map() padding for IE8 and below.

+8
source
 document .getElementsByTagName("ul")[0] .getElementsByTagName("li")[0] .style.color = "blue"; 
+3
source

If you only need to change the style, use CSS: first-child

 ul > li:first-child { color: blue; } 

works even in IE7 http://caniuse.com/#feat=css-sel2

http://jsfiddle.net/Tymek/trxe3/

+3
source

Since the only valid <ul> child element is <li> , you can do this:

 var firstLI = document.getElementsByTagName('ul')[0].children[0]; 
+1
source

Also consider sizzle , depending on your needs. Smaller than jQuery, but handles all your normalization of the selector.

0
source

Using basic DOM operations:

 var ul = document.getElementById('id of ul'); var child = ul.childNodes[0]; 
0
source

Source: https://habr.com/ru/post/1443443/


All Articles