问题描述
可能有人问过,但滚动浏览大约40多个搜索结果只显示了jQuery解决方案。假设我想在无序列表中获取第一个项目并为其应用新的文本颜色,并且单独使用它。使用jQuery很简单。
This may have been asked, but scrolling through about 40+ search results reveals only the jQuery solution. Let's say I want to get the first item in an unordered list and apply a new text color to it, and it alone. This is simple with jQuery.
标记 - >
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
使用jQuery - >
With jQuery ->
$("ul > li:first").css("color", "blue");
问题是,如何实现没有 jQuery?
Question is, how do I achieve this without jQuery?
解决方案:
我发现这种方法适用于所有浏览器(包括IE7 +) - >
SOLUTION:I found this method to work across all browsers (inc IE7+) ->
document
.getElementsByTagName("ul")[0]
.getElementsByTagName("li")[0]
.style.color = "blue";
推荐答案
您可以使用 querySelector
(不支持IE7及更低版本):
document.querySelector("ul > li")
或 querySelectorAll
:
document.querySelectorAll("ul > li")[0]
或 getElementsByTagName
:
document.getElementsByTagName("ul")[0]
.getElementsByTagName("li")[0]
改变的最佳方式风格IMO是设置一个类。您可以通过设置(或扩展)结果元素的 .className
属性来完成此操作。
The best way to change style IMO is to set a class. You do this by setting (or expanding) the .className
property of the resulting element.
否则,您可以使用 .style
属性设置各个样式。
Otherwise you can set the individual styles using the .style
property.
更新
update
作为指出,也许你想先 li
所有 ul
元素。在这种情况下,我会像这样使用 querySelectorAll
:
document.querySelectorAll("ul > li:first-child")
Then iterate the result to set the style.
要使用 getElementsByTagName
,您可以这样做:
To use getElementsByTagName
, you could do this:
var uls = document.getElementsByTagName("ul");
var lis = [].map.call(uls, function(ul) {
return ul.children[0];
});
你需要一个 Array.prototype.map()
为IE8和更低的垫片。
You'll need an Array.prototype.map()
shim for IE8 and lower.
这篇关于获得第一个< li>没有jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!