Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get link name in javascript

Example

<a href="example.html">Example Name</a>

I would like to get "Example Name"

I know I can do this with regex, but I'm looking for a simpler, faster approach. The closest I came was with Jquery using the .attr("href") attribute. I tried putting .attr("title"), but that doesn't work since I technically don't have a title there.

like image 888
stan Avatar asked Jul 25 '11 01:07

stan


People also ask

How do we take the text of the link?

Use the textContent property to get the text of a link element, e.g. const text = link. textContent . The textContent property will return the text content of the <a> element and its descendants. If the element is empty, an empty string is returned.

What is LINK HREF in JavaScript?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).


2 Answers

.text()
like image 166
Lightness Races in Orbit Avatar answered Oct 16 '22 07:10

Lightness Races in Orbit


Try this

var t = $('a').text();
alert(t);

http://jsfiddle.net/jasongennaro/gZsbW/

Of course, this targets the first link it encounters. Better if you can hook it to an ID.

Example

<a href="example.html" id="linkName">Example Name</a>

Then

var t = $('#linkName').text();
like image 40
Jason Gennaro Avatar answered Oct 16 '22 08:10

Jason Gennaro