Search code examples
javascripthtmlgetelementsbytagname

Specifying an index for getElementsByTagName


Im trying to find a way to specify an index number for the selected node from the button but i failed in getting the logic for it , I tried running a For loop but it'd just call all the buttons while i want the clicked button only to do the function HTML:

    <div>
            <button onclick="Change()">Change Color</button>
            <button onclick="Change()">Change Color</button>
            <button onclick="Change()">Change Color</button>
            <button onclick="Change()">Change Color</button>
            <button onclick="Change()">Change Color</button>
    </div>

CSS:

.ChangedColor{
    color:red;
}

JS:

function Change(){
    var y = document.getElementsByTagName("button")[y.length];
    y.classList.toggle("ChangedColor");
}

Im pretty sure the logic im using is wrong but i cant think of a way other than loops , Even with that , It did not work and showed an error. Could someone tell me how to specify an index depending on which button was clicked by the user ?


Solution

  • Would something like this be of help to you?

        <div>
                <button onclick="Change(this)">Change Color</button>
                <button onclick="Change(this)">Change Color</button>
                <button onclick="Change(this)">Change Color</button>
                <button onclick="Change(this)">Change Color</button>
                <button onclick="Change(this)">Change Color</button>
        </div>
    
    function Change(ix){
      ix.classList.toggle("ChangedColor");
    }