简体   繁体   中英

How to get href Text using CSS selectors

I have the following HTML below from Wikipedia main page at https://www.wikipedia.org/ . I'm trying to get the href text

//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.

[<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

getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); 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:

 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:

$('.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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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