Reputation: 332
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 077 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 077 000+ articles</small></a>]
Any advice is much appreciated.
Upvotes: 6
Views: 7145
Reputation: 32145
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 077 000+ articles</small>
</a>
</div>
Upvotes: 3
Reputation: 22643
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 077 000+ articles</small>
</a>
</div>
Upvotes: 2
Reputation: 206078
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 077 000+ articles</small>
</a>
</div>
Upvotes: 2