Open multiple links on a webpage using javascript

I have a webpage which has multiple links. What I want to do is I want to open all the links in different windows using javascript. As of now, my code looks like below. All the links have common calss “myClass” and different “id”.

$( document ).ready(function() {

var elements = document.getElementsByClassName("myClass");

for (var i = 0; i < elements.length; i++) {

    alert(elements[i].getAttribute("id"));

    $(elements[i].getAttribute("id")).onclick();
}})

What am I doing wrong? Could anyone help me on this. Any help would be much appreciated.

Answer

Instead of taking the id and trying invoke onclick() event manually, you can retrieve the href attribute and pass it to the window.open method.

for (var i = 0; i < elements.length; i++) {

    var url = elements[i].getAttribute("href");

    window.open(url);
}})

Read more about window.open here. https://developer.mozilla.org/en-US/docs/Web/API/Window.open

However, this might not be well accepted by the browsers, I suspect that they will prevent opening that many windows via javascripts. (Blocking Popups).

Leave a Reply

Your email address will not be published. Required fields are marked *