2016-03-10 34 views
-1

如果li元素中的文本爲「OFF」,我想更改li元素的顏色。jQuery更改ul節點的css

HTML結構:

-> OL 
    -> UL 
     -> UL 
     -> LI - if LI text is "OFF" its color should be red. 
    -> UL 
    -> UL 
     -> LI 

我做了這樣的事情,但不工作:

$("#content").children().each(function() { 
    $(this).children().each(function() { 
    if (this.text == "OFF") 
     $(this).css({ 'color': 'red' }); 
    }) 
}) 
+0

你是什麼意思是關閉?你能提供你的HTML嗎? – Aaron

+0

@Aaron如果文本內容是「關」。 –

回答

1

你做錯了。你需要做的是這樣的:

$("#content").find("li").each(function() { 
    if ($(this).text().trim() == "OFF") 
    $(this).css({ 'color': 'red' }); 
}); 

通過文本片段

$(function() { 
 
    $("#content").find("li").each(function() { 
 
    if ($(this).text().trim() == "OFF") 
 
     $(this).css({ 'color': 'red' }); 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery-2.1.4.js"></script> 
 
<ol id="content"> 
 
    <li> 
 
    <ul> 
 
     <li>OFF</li> 
 
    </ul> 
 
    </li> 
 
    <li> 
 
    <ul> 
 
     <li>ON</li> 
 
    </ul> 
 
    </li> 
 
</ol>