8

how to get text from an link with onclick ?

my code :

<a href='#' onclick='clickfunc()'>link</a>

 function clickfunc() {
        var t = text();
        alert(t);
    }

text = link

0

8 Answers 8

17

try this

 <a href='#' onclick='clickfunc(this)'>link</a>

 function clickfunc(obj) {
    var t = $(obj).text();
    alert(t);
 }

well, it is always better and recommended to avoid inline javascript(onclick()).. rather you can use

$('a').click(function(){
    alert($(this).text());
});

or to be more specific...give an id to <a> and use id selector

 <a href='#' id='someId'>link</a>

 $('#someId').click(function(){
    alert($(this).text());
});
Sign up to request clarification or add additional context in comments.

Comments

5
<a href='#' onclick='clickfunc(this)'>link</a>

clickfunc = function(link) {
  var t = link.innerText || link.textContent;
  alert(t);
}

JSFiddle Demo

2 Comments

Use link.textContent || link.innerText for full browser support. Or stick to jQuery’s .text()
@David: You are right about textContent. jQuery was not mentioned so I guessed poster wanted to do without.
3

try this with vanilla javascript

<a href='#' onclick='clickfunc(this)'>link</a>

 function clickfunc(this) {
    var t = this.innerText;
    alert(t);
}

Comments

2

You can do this:

HTML

<a href='#' onclick='clickfunc(this)'>link</a>

JS

function clickfunc(obj) {
    var t = $(obj).text();
    alert(t);
}

Demo: Fiddle

Comments

1

With jQuery you can do it this way.

$(document).on('click', 'a', function(event){
    event.preventDefault();

    alert($(this).text);
});

Comments

0

html

<a href='#' id="mylink" onclick='clickfunc()'>link</a>

js

function clickfunc() {
            var l = document.getElementById('mylink').href; //for link
            var t = document.getElementById('mylink').innerHTML; //for innerhtml
            alert(l);
            alert(t);
        }

Comments

0

Try this easy using jQuery

$('a').click(function(e) {
  var txt = $(e.target).text();
  alert(txt);
});

Comments

0

Since you use javascript not jquery, do the following

<a href='#' onclick='clickfunc(this)'>link</a>

 function clickfunc(obj) {
        var t = obj.innerText;
        alert(t);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.