简体   繁体   English

如何使用CSS选择器获取href文本

[英]How to get href Text using CSS selectors

I have the following HTML below from Wikipedia main page at https://www.wikipedia.org/ . 我在Wikipedia主页上的https://www.wikipedia.org/上具有以下HTML。 I'm trying to get the href text 我正在尝试获取href文本

//en.wikipedia.org/

<div class="central-featured-lang lang1" lang="en">
<a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box">
<strong>English</strong><br>
<em>The Free Encyclopedia</em><br>
<small>5&nbsp;077&nbsp;000+ articles</small>
</a>
</div>

I've tried this $$('.central-featured-lang.lang1 a[href$=".org/"]') but I still get the whole output, not just the href text. 我已经试过这个$$('.central-featured-lang.lang1 a[href$=".org/"]')但是我仍然得到了整个输出,而不仅是href文本。

[<a href=​"/​/​en.wikipedia.org/​" title=​"English — Wikipedia — The Free Encyclopedia" class=​"link-box">​…​</a>​<strong>​English​</strong>​<br>​<em>​The Free Encyclopedia​</em>​<br>​<small>​5&nbsp;077&nbsp;000+ articles​</small>​</a>​]

Any advice is much appreciated. 任何建议深表感谢。

错误消息结果

Use DOM Element getAttribute() Method 使用DOM元素的getAttribute()方法

getAttribute() returns the value of a specified attribute on the element. getAttribute()返回元素上指定属性的值。 If the given attribute does not exist, the value returned will either be null or "" (the empty string); 如果给定的属性不存在,则返回的值将为null或“”(空字符串);否则为0。 see Notes for details. 有关详细信息,请参见注释。

 var element = document.querySelector('a.link-box'), link = element.getAttribute('href'); alert(link) 
 <div class="central-featured-lang lang1" lang="en"> <a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box"> <strong>English</strong> <br> <em>The Free Encyclopedia</em> <br> <small>5&nbsp;077&nbsp;000+ articles</small> </a> </div> 

In Javascript you can use document.querySelector along with href attribute, like this: 在Javascript中,您可以将document.querySelectorhref属性一起使用,如下所示:

 var url = document.querySelector('.central-featured-lang.lang1 a[href$=".org/"]').href; alert(url); 
 <div class="central-featured-lang lang1" lang="en"> <a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box"> <strong>English</strong> <br> <em>The Free Encyclopedia</em> <br> <small>5&nbsp;077&nbsp;000+ articles</small> </a> </div> 

Use the .attr() Method: 使用.attr()方法:

$('.central-featured-lang.lang1 a[href$=".org/"]').attr("href")

 var url = $('.central-featured-lang.lang1 a[href$=".org/"]').attr("href"); alert( url ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="central-featured-lang lang1" lang="en"> <a href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia" class="link-box"> <strong>English</strong><br> <em>The Free Encyclopedia</em><br> <small>5&nbsp;077&nbsp;000+ articles</small> </a> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM