william ganrot william ganrot - 4 years ago 163
Javascript Question

get element by tag name [this]?

First a short background. So I just started practicing using API's. With the one I'm working with right now, I'm loading a DIV which have alot of links in it which I have to give a new purpose. I managed to prevent the default onclick-function. Now I need do save the clicked link "innerHTML" attribute.

var nextPage = document.getElementsByTagName("a")[this].innerHTML;


with [this] I tried to target the clicked link, but it didn't work. Hopefully you understands what I'm trying to do. If so, is there any way I an solve this problem?

Thanks!

EDIT:

$("#content, a").click(function(event){
event.preventDefault();

var x = document.getElementsByTagName("a")[0].innerHTML;
console.log(x)



getPage(x);
});

Answer Source

You can add an onclick listener to all the a tags elements

var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
  links[i].onclick = clickHandler;
}

function clickHandler(event) {
  console.log(this.innerHTML);
}
<a>Link a</a>
<a>Link b</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download