Javascript - 选择元素子元素的第一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21406644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - Select first element of child of child of element
提问by Juggernaut
I have the following HTML:
我有以下 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.
现在我想通过Javascript在div“list”中的div“items”中的第一个“ul”中选择第一个“li”。
回答by dtech
You can use any combination of getElementById
, getElementsByClassName
and getElementsByTagName
.
您可以使用getElementById
,getElementsByClassName
和 的任意组合getElementsByTagName
。
var divs = document.getElementsByClassName('items');
var uls = divs[0].getElementsByTagName('ul');
var lis = uls[0].getElementsByTagName('lo');
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:
如果你给一些元素一个 id 会更容易,那么你可以使用 an
getElementById
而不是笨重的getElements_
并且不必处理数组:
var div = document.getElementById('items'); // If the right <div> has an id="items"
var uls = div.getElementsByTagName('ul');
var lis = uls[0].getElementsByTagName('lo'); // 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:
最简单的解决方案可能是使用像 jQuery 这样的库,您可以在其中使用选择器执行此操作:
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).
编辑:如果您不能使用 jQuery 并且排除旧浏览器(主要是 IE7 或更低版本)没有问题,我会推荐 David Thomas 的解决方案。
回答by David says reinstate Monica
If you're targeting modern browsers, I'd suggest:
如果您的目标是现代浏览器,我建议:
var importantLi = document.querySelector('.list .items li');
References:
参考:
回答by Alexander
your div would normally be <div id="items">
or <div id="items" class="items">
since a div with id is unique on a page.
您的 div 通常是<div id="items">
或<div id="items" class="items">
因为带有 id 的 div 在页面上是唯一的。
Then
然后
firstLi = document.getElementById("items").firstChild.firstChild;
回答by Siva Charan
回答by mrakodol
you can try this <script>$('.items ul li:first').val()</script>
你可以试试这个 <script>$('.items ul li:first').val()</script>