Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Error Message Result

like image 389
Ming Avatar asked Apr 29 '16 01:04

Ming


People also ask

Can we use text () in CSS selector?

For locating elements by using their text contents, CSS selectors and XPath provide methods to find text within the elements. If an element contains specific text, this will return the element back to the test.

Can you do HREF in CSS?

You cannot simply add a link using CSS. CSS is used for styling. You can style your using CSS. If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.


1 Answers

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>
like image 66
cнŝdk Avatar answered Sep 19 '22 23:09

cнŝdk