Search code examples
javascripthtmljqueryhref

Loop through href using JavaScript


I have an array geneList where loop is applied over it. So, that href will change as loop iterate where hangoutButton will automatically click and redirect to the given url. Sounds Simple

Problem:- Loop is iterating you can see into console that your is iterating but href value is not iterating. It Like href is been stuck on first index only. When page is redirect you will see array of first index into key on every iteration. You can observe key is iterating in console.

Can anyone please help

Thank you in advance........

var geneList= ["123", "456", "678","2345"];
   
geneList.forEach(function(key){
                // GSEA Redirect Button
                var sample= document.createElement('a');
                sample.href = "forEdit3.php?randNum=" + key;
                sample.target = "_blank";
                sample.style.display = "none";
                var samplebutton = document.createElement('button');
                samplebutton .innerHTML = "BarPlot";
                samplebutton .className = "btn";
                samplebutton .id = "autoClickbarPlot";
                forPlot.appendChild(sample);
                sample.appendChild(samplebutton );
                var hangoutButton = document.getElementById("autoClickbarPlot");
                hangoutButton.click();
                console.log(key);
            });

Solution

  • The reason why is clicking the first element is that you are using the same ID to multiple elements, so when you set hangoutButton will always return the first item as you are trying to select by the ID.

    To make it work you concatenate your key value to the element ID.

    Something like this:

    sampleButton.id = "autoClickbarPlot_" + key;

    and then

    var hangoutButton = document.getElementById("autoClickbarPlot_" + key);

    This should be enough for you to select your desired hangoutButton