我如何访问<li>jQuery is for chumps!</li>
元素?
它没有ID,所以我不知道该怎么做。
我要将它存储在变量
<!DOCTYPE html>
<html>
<head>
<title>Simplify, Simplify</title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<div> Remember!
<ul>
<li>
<ol>
<li>Start with the function keyword</li>
<li>Inputs go between ()</li>
<li>Actions go between {}</li>
<li>jQuery is for chumps!</li>
</ol>
</li>
<li>Inputs are separated by commas.</li>
<li>Inputs can include other functions!</li>
</ul>
</div>
</body>
</html>
答案 0 :(得分:1)
你可以这样做:
var selector = $('ol li:last');
更具体的是将id或类添加到父div并执行如下操作:
var selector = $('#parent ol li:last');
或者,如果它可以在你的任何地方,那么你可以使用contains:
var selector = $('#parent ol li:contains("jQuery is for chumps!")');
答案 1 :(得分:1)
您可以在此处使用多个选择器
//using the contents of the li, using contains() can return partial matches so need to be careful about it
$('ul ol li').filter(':contains("jQuery is for chumps!")').css('color', 'red');
//using the position - it targets the last child of the ol element
$('ul ol li:last-child').css('background-color', 'green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>Remember!
<ul>
<li>
<ol>
<li>Start with the function keyword</li>
<li>Inputs go between ()</li>
<li>Actions go between {}</li>
<li>jQuery is for chumps!</li>
</ol>
</li>
<li>Inputs are separated by commas.</li>
<li>Inputs can include other functions!</li>
</ul>
</div>
答案 2 :(得分:0)
没有jQuery:document.getElementsByTagName('li')[5]
然后,您可以使用if语句检查它是否具有正确的内容。
var i = 0;
while(i <= document.getElementsByTagName('li').length()){
if(document.getElementsByTagName('li')[i].innerHTML == "jQuery is for Chumps"){
//Do Something
}
i++;
}
答案 3 :(得分:0)
首先是您的HTML,以便更快地添加查询 - 添加ID。否则你必须从body标签看,这可能需要一些时间。
<ul id="menu-bar">
<li>
<ol>
<li>Start with the function keyword</li>
<li>Inputs go between ()</li>
<li>Actions go between {}</li>
<li>jQuery is for chumps!</li>
</ol>
</li>
<li>Inputs are separated by commas.</li>
<li>Inputs can include other functions!</li>
</ul>
现在选择器,通过检查最后一个节点
var lastElement = $('#menu-bar > li > ol > li:last');
或按内容(如果您支持多种语言则不起作用)
var lastElement = $('#menu-bar > li > ol li:contains("jQuery is for chumps!")')
答案 4 :(得分:0)
获取ol
元素的直接子元素:
var children = $("ol > li");
获取具体元素:
var element = children.last();
从元素中获取文本:
var text = element.html();