Ronedog
Ronedog

Reputation: 2331

getting the parent element text using jquery from within a js function

I would like to figure out a way to retrieve the the link text users click on from within my webapp... i'm wondering if jquery can do it.

Heres what a link would look like:

<span onclick="myfunction();">Link Text 1</span>

The function "myfunction()" is located inside a .js file that gets incluced into the page

When the user clicks on the span tag, I would like to capture the text from the span tag that called the myfunction(), then place the text "Link Text 1" into a js variable I would then use to update my database with.

I know I could do this:

<span onclick="var xx = $(this).text(); myfunction(xx);">Link Text 1</span>

But I have too many calls to this one function that rewriting the click events would be too much...i'm wondering how I can accomplish the same thing from within the "myfunction()" code using jquery to retrieve the text?

Any ideas?

Thanks in advance.

Upvotes: 0

Views: 68

Answers (2)

zachzurn
zachzurn

Reputation: 2201

In the html:

<span onclick="myfunction(this)">Link Text 1</span>

Javascript function:

function myfunction(elem){
    var theText =$(elem).text();
}

Upvotes: 0

Ram
Ram

Reputation: 144709

try this:

<span>Link Text 1</span>

$('span').click(function(e){
   var txt = $(this).text() // gets span's text
})

Upvotes: 1

Related Questions