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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With