我正在构建一个 Chrome 扩展程序(因此只能使用 JavaScript),我需要使用 heading2
类获取驻留在 h2
中的链接。
但是,该类有多个 h2
项(此处未显示),我不知道链接将指向什么,因为它每月更改一次。
在这个例子中,标题的内容是“Think before you tweet”。它将始终位于另一个包含“特色主题”字样的标题下。
我想要得到的是h2
项的href=
中的/think_before_you_tweet
。它表明我已经完成了 h2
下的主题,但情况并非总是如此。
这是网站的代码:
<div class="chosen_for_you_section">
<div class="internal_container">
<h2 class="section_header"><img src="/public/s360/img/360-spinner.png" class="s360LogoHeader">Featured Topic <a href="#require_topic" class="fancybox"><i class="fa fa-info-circle"></i> <span class="infoTxt">Read about what to do</span></a></h2>
<article class="article_block masonry_item " data-article_id="431">
<div class="article_image">
<a href="/think_before_you_tweet"><img src="/thumb/public/media/nh/images/twitter_tweet_think_before_send.png?q=&h=278" /></a>
<i class="fa fa-check-square-o article_complete article_type_icon" title="Article"></i>
<div class="action_icons">
<span class="like "><a title="Favorite"><i class="fa fa-heart"></i></a></span>
</div>
</div>
<header>
<h2 class="heading2"><a href="/think_before_you_tweet">Think Before You Tweet!</a></h2>
<div class="article_required_complete">Congratulations, you've completed this required topic.</div>
<div class="category_blocks">
<p>
<a href="/content/category/Social+Media">Social Media</a>
</p>
</div>
</header>
</article>
<div class="focus_items">
<div class="home_side">
<p>
<img alt="" src="" style="width: 430px; height: 422px;" /><!-- I hid the img src here because it reveals some personal information and is not important -->
</p>
<p></p>
</div>
</div>
</div>
</div>
我可以在我的扩展中使用 jQuery,但我没有任何后端功能。
最佳答案
使用 jQuery :contains选择器:
$('h2.section_header:contains("Featured Topic") + article a')[0].href
关于javascript - 从没有 id 或 class 的元素中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144444/