我不知道这是否是正确的方法,但我尝试使用querySelector来获取位于第一个超链接中的第二个跨度。
<ul className="h-topnav menu horizontal">
<li>
<Link to={"/"} ref="link" className="margin-top-10">
<span className="underline-grey large underlined">
<span className="font-black">H</span><span className="grey-dark">ome</span></span>
</Link>
</li>
<li>
<Link to={"/about"} ref="link" className="margin-top-10">
<span className="underline-grey large underlined">
<span className="font-black">A</span><span className="grey-dark">bout</span></span>
</Link>
</li>
<li>
<Link to={"/jobs"} ref="link" className="margin-top-10">
<span className="underline-grey large underlined">
<span className="font-black">J</span><span className="grey-dark">obs</span></span>
</Link>
</li>
</ul>
我可以通过&#39; h-topnav&#39;来获取元素。作为一个标记,但现在我试图从这一点深入挖掘:
theUL.querySelector('li[0] a span[1].textContent').to.equal("Home")
答案 0 :(得分:1)
您可以使用
theUL.querySelector("li:nth-child(1) span").textContent.trim()
请注意致电.trim()
,以便从调用.textContent
的结果中删除空格
window.onload = function() {
var theUL = document.querySelector("ul");
console.log(theUL.querySelector("li:nth-child(1) span").textContent.trim() === "Home");
}
<ul className="h-topnav menu horizontal">
<li>
<Link to={ "/"} ref="link" className="margin-top-10">
<span className="underline-grey large underlined">
<span className="font-black">H</span><span className="grey-dark">ome</span></span>
</Link>
</li>
<li>
<Link to={ "/about"} ref="link" className="margin-top-10">
<span className="underline-grey large underlined">
<span className="font-black">A</span><span className="grey-dark">bout</span></span>
</Link>
</li>
<li>
<Link to={ "/jobs"} ref="link" className="margin-top-10">
<span className="underline-grey large underlined">
<span className="font-black">J</span><span className="grey-dark">obs</span></span>
</Link>
</li>
</ul>
答案 1 :(得分:0)
您正在搜索:first-child
伪选择器:
var text = theUL.querySelector('li:first-child > a > span').textContent
console.log(text)
<ul class="h-topnav menu horizontal">
<li>
<a href="/" ref="link" class="margin-top-10">
<span class="underline-grey large underlined">
<span class="font-black">H</span><span class="grey-dark">ome</span></span>
</a>
</li>
<li>
<a href="/about" ref="link" class="margin-top-10">
<span class="underline-grey large underlined">
<span class="font-black">A</span><span class="grey-dark">bout</span></span>
</a>
</li>
<li>
<a href="/jobs" ref="link" class="margin-top-10">
<span class="underline-grey large underlined">
<span class="font-black">J</span><span class="grey-dark">obs</span></span>
</a>
</li>
</ul>
顺便说一句:我可能还建议使用:first-letter
CSS伪选择器设置链接文本样式,这样可以大大简化标记。
.h-topnav span:first-letter {
color: black;
}
.h-topnav span {
color: gray;
}
<a href="/" ref="link" class="margin-top-10">
<span class="underline-grey large underlined">Home</span>
</a>
答案 2 :(得分:0)
您可以使用first-child
的{{1}}和li
的{{1}},如下所示。
nth-child(1)
span
答案 3 :(得分:0)
这是最简单的解决方案:li:nth-child(1)span:nth-child(1)