Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get text from an link with onclick in javascript

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

like image 906
john Avatar asked Oct 28 '13 11:10

john


3 Answers

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());
});
like image 163
bipen Avatar answered Oct 28 '22 02:10

bipen


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

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

JSFiddle Demo

like image 32
Alexander Presber Avatar answered Oct 28 '22 04:10

Alexander Presber


try this with vanilla javascript

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

 function clickfunc(this) {
    var t = this.innerText;
    alert(t);
}
like image 42
Nauphal Avatar answered Oct 28 '22 04:10

Nauphal