Home > front end >  js script only work for one element, only the first one
js script only work for one element, only the first one

Time:03-17

I have multiple checkbox elements on my page, whenever someone clicks on each of them, their color and text are changed, I was able to do that with CSS, but I wanted to change the icon in the checkbox button also, So I Use javascript in my HTML code but when I run the script it only works for one element, only the first one, so that means the icon only change for the first checkbox button but it is not working for all the other button, I tried to give all my checkbox button unique ID but I still have the same issue

This is checkbox 1 and 2 when not selected

This is checkbox 1 and 2 when selected

Here's the script I run to do that:

Ps: I use this script for all the other checkbox buttons, I already tried to change the id of the buttons to match HTML and the script id but still working only for the first one.

  document.getElementById ('checkbox').addEventListener ('click', function (ev) {
    document.getElementById('icon').classList[ ev.target.checked ? 'add' : 'remove'] ('fa-circle-check');
  }, false);

Any help would be welcome, please.

CodePudding user response:

  document.getElementById ('checkbox').addEventListener ('click', function (ev) {
    document.getElementsByClassName('icon').classList[ ev.target.checked ? 'add' : 'remove'] ('fa-circle-check');
  }, false);

getElementsByClassName('icon') will select all classes that have that value.

CodePudding user response:

document.getElementById will only return the first element with the specified id, therefore giving multiple elements the same id won't help. I suggest to check out document.getElementsByClassName providing the check boxes the same class instead.

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

CodePudding user response:

Do NOT use the same ID on multiple elements. It will only return the first one it finds. You should be setting multiple items with the class instead. You can then do.

document.getElementByClassName('YourClassNameHere)

or

document.querySelectorAll('.YourClassNameHere') *** NOTE the .... You will need . for the determining a class. # would determine for an ID.

CodePudding user response:

you can use this but it this method returns a nodelist so you'd have to use a loop to add event listener to each of the checkboxes:

//if you're using class selector
 document.querySelectorAll('.checkbox');

//if you're using id selector
 document.querySelectorAll('#checkbox')
  • Related