Question: append onclick to links javascript

Question

append onclick to links javascript

Answers 3
Added at 2017-01-01 12:01
Tags
Question

To append:

_target="_blank"

To all links in an HTML page I use:

var links = document.querySelectorAll("a");
  for (var i=0;i<links.length;i++) {
    links[i].target="_blank";
  }

But for some reason, when I use the exact same code and try to append:

onclick="alert(2)"

Like so:

var links = document.querySelectorAll("a");
  for (var i=0;i<links.length;i++) {
    links[i].onclick="alert(2)";
  }

It does not work.

Can anyone show me how to do this? (preferably in javascript instead of jQuery)

thanks!

Answers to

append onclick to links javascript

nr: #1 dodano: 2017-01-01 12:01

Try

links[i].onclick = function() { alert(2); };
nr: #2 dodano: 2017-01-01 12:01

You can use your original query with a slight modification:

var links = document.querySelectorAll("a");
  for (var i=0;i<links.length;i++) {
    links[i].onclick=function() { alert(2) };
  }
nr: #3 dodano: 2017-01-01 12:01

As other answers show, the onclick property should contain a function. If you really want to assign a Javascript code string, you can do it with setAttribute.

var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
  links[i].setAttribute('onclick', "alert(2)");
}
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<a href="#">Link 4</a>

Source Show
◀ Wstecz