Roland
Roland

Reputation: 57

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.

Upvotes: 0

Views: 196

Answers (2)

dhouty
dhouty

Reputation: 1989

It looks like you are using jQuery, so a simple solution would be

$(".myClass").each(function() {
    window.open(this.href); 
});

Otherwise a pure JavaScript approach would be

var elements = document.getElementsByClassName("myClass");
for (var i=0; i<elements.length; i++) {
    window.open(elements[i].getAttribute("href"));
}

Upvotes: 0

BuddhiP
BuddhiP

Reputation: 6451

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).

Upvotes: 1

Related Questions