Search code examples
javascriptnodelistgetelementsbyname

JavaScript - getElementsByName


I was trying to learn some JavaScript and make a modal for my webpage through this tutorial Building Your Own JavaScript Modal Plugin

The problem actually came at the end when I realized that he catches element by ID and I have multiple anchor tags that are supposed to open modal on click. I tried to change the ID to name but I realized I get the next code and only one works and I can't find the solution. I was searching for hours.

If you have suggestion how to catch elements differently or how to solve this one would be helpful.

var triggerButton = document.getElementsByName('trigger');

triggerButton[0].addEventListener('click', function() {
myModal.open();

triggerButton[1].addEventListener('click', function() {
myModal.open(); // if i put like this etc all my links work and etc.


});

Solution

  • First of all, it's best to use the attribute class for this:

    <a class="trigger"> ... </a>
    

    Then, in JS, get them with:

    var triggerButtons = document.getElementsByClassName("trigger");
    

    Then, loop through each one and add event listeners like you did:

    for(var i = 0; i < triggerButtons.length; i++) {
        triggerButton[i].addEventListener('click', function() {
            myModal.open();
        });
    }
    

    (Here is a working JS example.)

    This is dynamic and is much easier than manually adding an event listener for each element.

    If you wanted to do this in jQuery, this would be much easier. You can achieve this all with this one-liner:

    $(".triggerButtons").click(function(){myModal.open();});
    

    (Here is a jQuery example.)