admin管理员组文章数量:1315982
<div class="A">
<section class="B" data-vr-zone="B">
<header class="C"> BarFoo</header>
<ul class="list">
<li data-vr-contentbox="">
<a href="/.../html">
<small>BarBar</small>
<span>Foo Bar foobarbar FooFoo?</span>
</a>
</li>
<li data-vr-contentbox="">
<a href="/.../html">
<small>BarBarBar</small>
<span>Foo foo FooFoo?</span>
</a>
</li>
I want to access the url in the HREF attribute. And the text in the SPAN -- Of only the first list item.
What I have works but I'm looking to learn a better way.
var url = $('div .A').children().children().children().children()[0].attribs.href;
var title = $('div .A').children().children().children().children()[0].children[2].children[0].data;
<div class="A">
<section class="B" data-vr-zone="B">
<header class="C"> BarFoo</header>
<ul class="list">
<li data-vr-contentbox="">
<a href="http://www.foobar./.../html">
<small>BarBar</small>
<span>Foo Bar foobarbar FooFoo?</span>
</a>
</li>
<li data-vr-contentbox="">
<a href="http://www.foofoobar./.../html">
<small>BarBarBar</small>
<span>Foo foo FooFoo?</span>
</a>
</li>
I want to access the url in the HREF attribute. And the text in the SPAN -- Of only the first list item.
What I have works but I'm looking to learn a better way.
var url = $('div .A').children().children().children().children()[0].attribs.href;
var title = $('div .A').children().children().children().children()[0].children[2].children[0].data;
1 Answer
Reset to default 6You want to use a better selector string to target the element & attribute of interest. Exactly how vague or precise you go involves trade-offs of coupling too tighly to the DOM structure and thus some irrelevant change to the HTML means your selector doesn't match anymore or using too vague a selector and matching more stuff than you intend.
- vaguest:
'a'
(find every anchor) '.A a'
(every anchor inside the div class="A")- Remended:
'.A li a'
(must be part of a list) - crazy specific:
'div.A section.B ul.list li a'
.
var link = $('.A li a');
var href = link.attr('href');
var spanText = link.find('span').first().text();
本文标签: javascriptHow to use CHEERIOjs for this HTMLStack Overflow
版权声明:本文标题:javascript - How to use CHEERIO.js for this HTML? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741994409a2409749.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论