Inside the onclick
function, this
is the element, and this.innerHTML
would give you its inner html.
Inside select_term
, this
is window
, because you've called it without any context. See how does the this keyword work for more details.
$
is an undefined variable. If you've defined it as jQuery, then $(this)
would give you a jQuery object wrapped around whatever element this
is. $(this).innerHTML
would give you undefined
because jQuery doesn't provide innerHTML
(it does have the html
function though).
If you want to get the innerHTML
of the a
element inside the select_term
function, then you have to either:
- Write JavaScript that isn't mired in the '90s and use
addEventListener
instead of an onclick
attribute
- Pass the element object to the
select_term
function
If you want to get the element using your first chunk of code, then you need to do the same thing, only with the event object.
The event handler function gets passed the event object as the first argument automatically, but the onclick
function which calls the select_term
function is the event handler. select_term
itself is not.
function select_term(e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (target.nodeType == 3) target = target.parentNode;
console.log(target.innerHTML);
}
document.querySelector("a").addEventListener("click", select_term);
<a href="#" style='text-decoration:none'>{{ descriptor.name|safe }}</a>
That said, you can just use currentTarget
instead of all the fiddling you are currently using to try to identify the element.
function select_term(e) {
var target = e.currentTarget;
console.log(target.innerHTML);
}
document.querySelector("a").addEventListener("click", select_term);
<a href="#" style='text-decoration:none'>{{ descriptor.name|safe }}</a>
NB: If you're writing href="#"
then you don't have a link and should not use <a>
. Consider <button type="button">...</button>
instead.