0

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.

4
  • Where are you binding the onclick handlers, what do they look like? Commented Sep 19, 2014 at 3:26
  • Are you getting error's? What is it doing that isn't right? Commented Sep 19, 2014 at 3:32
  • @LJ_1102 I have integrated this snippet under my HTML head tab. Commented Sep 19, 2014 at 3:33
  • @Sean F This code just throws an alert with id number of the very first link. It isn't opening up other links in different windows, which I intend to do. Commented Sep 19, 2014 at 3:34

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Glad I could help. Please accept the answer if it worked, and vote of course :)
A little late, and you correctly said the browser blocks the pop-ups, is there a way around this pop-up problem...
There is no solution to that as far as I know, If your users trust your site and accept popups are required, then they can configure their browsers to allow popups from your site. But that has to be done individually by each user.
Got it. I will have a look into it. Thank you for the quick repies!!
0

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"));
}

1 Comment

Thank you for the help @dhouty. I tried BuddhiP instructions and it seems to be working fine. Again thank you for the quick reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.