Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting calling element (anchor) dynamically with JavaScript

How would I go about getting the text of an anchor tag using JavaScript. I know how to do this by attaching an ID to the tag but I was wondering if there's anyway to do it using the "this" keyword.

Example HTML Snippet:

<ul>
    <li><a href="javascript:alertText(this);">Link One</a></li>
    <li><a href="javascript:alertText(this);">Link Two</a></li>
</ul>

JavaScript Function:

function alertText(callingElement) {
    alert(callingElement.text);
}

This is not working (alert is printing out "undefined") because the "this" keyword seems to be pointing at the Window object instead of the anchor that called the function.

Using JQuery is an option if it is necessary.

like image 682
Deity Avatar asked Oct 10 '22 09:10

Deity


1 Answers

You can use .innerHTML, but to pass this, you need to use the onclick attribute.

<ul>
    <li><a href="#" onclick="alertText(this);">Link One</a></li>
    <li><a href="#" onclick="alertText(this);">Link Two</a></li>
</ul>

JS:

function alertText(callingElement) {
    alert(callingElement.innerHTML);
}

Or you can use .innerText or .textContent depending on the user's browser.

JS:

function alertText(callingElement) {
    alert(callingElement.textContent || callingElement.innerText);
}

UPDATE:

Ah, wait, it's an anchor element, so it does have a .text property, so your original function will work (at least in browsers that support HTML5).

JS:

function alertText(callingElement) {
    alert(callingElement.text);
}
like image 63
RightSaidFred Avatar answered Oct 17 '22 11:10

RightSaidFred