简体   繁体   中英

Styling specific <li> element in unordered list <ul>

For example, I have the following html:

<ul>
       <li>1</li>
       <li>2</li>
       <ul>
          <li>1</li>
           <ul>
               <li>1</li>
               <li>2</li>
           </ul>
           <li>2</li>
       </ul>
   </ul>
   <ul>
       <li>1</li>
       <li>2</li>
   </ul>
   <ul>`enter code here`
       <li>1</li>
       <li>2</li>
</ul>

And, i want to style only li elements which have value = 1 . I tried this in jQuery and it works , but i want to know if there is a better way to perfom this.

My approach:

$("ul li").each(
   function(){
       if($(this).text() == "1"){
           $(this).css("color","red");
       }
   });

You can use :contains()

$("ul li:contains('1')").css("color","red");

fiddle

If you have li elements with other values than 1 or 2 you can use jquery .filter()

$("ul li").filter(
    function(){
        return $(this).text() == 1;
    }).css("color","red");

fiddle

You can also use the css method:

$('li').css('color', function(_, currentColor) {
    return $.trim(this.textContent) === '1' ? 'red' : null;
});

From jQuery .css() 's documentation:

Note: If nothing is returned in the setter function (ie. function( index, style ){} ), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

If you have only 1 and 2 you can use following

$("li:contains(1)").css("color","red");

It will include an li if the content is 21 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM