Home > Mobile >  Get element by id through Variable?
Get element by id through Variable?

Time:10-31

<form>
      <div><button id="1">1</button></div>

      <div><button id="2">2</button></div>
      <div><button id="3">3</button></div>
      <div><button id="4">4</button></div>
      <div><button id="5">5</button></div>
      <div><button id="6">6</button></div>
      <div><button id="7">7</button></div>
      <div><button id="8">8</button></div>
      <div><button id="9">9</button></div>
      <input type="submit"  value="Submit" onclick="subFunc()">
      </form>
const btn = document.getElementById('1');

btn.addEventListener('click',function hadleclick(){
    btn.style.background = '#53E247';
})

I want know how can i pass id by variable is it possible or i have get every button id sepratley? also i want know how can implement onClick color changing one button at single time rest should have color prop of none.

CodePudding user response:

Firstly, you didn't add specific class for buttons, and you didn't add forEach loop for catch whole elements. You can change code like this:

<form>
    <div><button id="1" > 1</button></div>
    <div><button id="2" >2</button></div>
    <div><button id="3" >3</button></div>
    <div><button id="4" >4</button></div>
    <div><button id="5" >5</button></div>
    <div><button id="6" >6</button></div>
    <div><button id="7" >7</button></div>
    <div><button id="8" >8</button></div>
    <div><button id="9" >9</button></div>
    <input type="submit"  value="Start set color" onclick="subFunc()">
</form>


<script>
    let btn = document.querySelectorAll('.changeColor');

    function subFunc(){
        e = event || window.event;
        e.preventDefault();

        btn.forEach( (it,i) => {
            it.addEventListener('click',function(ev){
                 ev.preventDefault();
                it.style.background = '#53E247';
             });
        })
    }
</script>

CodePudding user response:

This is really just an example, but it will work:

let buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i  ) {
    buttons[i].addEventListener('click', function(){
       buttons[i].style.background = '#53E247';
       for (let j = 0; j < buttons.length; j  ) {
           if (buttons[i].id !== buttons[j].id) {
               buttons[j].style.background = "unset";
           }
       }
    });
}

CodePudding user response:

You can select your buttons (you don't need ids) with :

document.querySelectorAll("form div button").forEach((e) => {});

Or you can use a class applied on buttons :

for (let e of document.getElementsByClassName("yourClass")) {}

Or you can make a single event listener by selecting the parent. In the snippet below, I add or remove the background-color by adding or removing a class :

document.getElementById("container").addEventListener("click", () => {
  if (event.target.tagName == "BUTTON") {
    if (document.querySelector("#container button.bg-green")) {
      document.querySelector("#container button.bg-green").classList.remove("bg-green")
    }
    event.target.classList.add("bg-green")
  }
})
.bg-green {
  background-color: #53E247;
}
<div id="container">
  <div><button>1</button></div>
  <div><button>2</button></div>
  <div><button>3</button></div>
  <div><button>4</button></div>
  <div><button>5</button></div>
  <div><button>6</button></div>
  <div><button>7</button></div>
  <div><button>8</button></div>
  <div><button>9</button></div>
</div>

CodePudding user response:

It is generally not a good idea to use inline event handlers.

Use event delegation. The handler in this snippet checks the click state of all buttons when the submit input is clicked. It only triggers for the submit control and buttons with a numeric id, having no color yet.

document.addEventListener(`click`, handle);

function handle(evt) {
  if ( evt.target.id &&
      !isNaN(evt.target.id) &&
      evt.target.tagName === `BUTTON` &&
      !evt.target.style.backgroundColor ) {
    console.clear();
    evt.target.style.backgroundColor = '#53E247';
    return console.log(`clicked button ${evt.target.id}`);
  }
  if (evt.target.id === `submit`) {
    console.clear();
    if ( ![...document.querySelectorAll(`button`)].find(v =>
        v.id && !isNaN( v.id) && !v.style.backgroundColor) ) {
      return console.log(`all buttons are clicked`);
    }
    return console.log(`you did not click all buttons`);
  }
}
.submitBttn {
  position: absolute;
  left: 20%;
  top: 1rem;
}
<div>
  <button id="1">1</button>
  <button id="2">2</button>
  <button id="3">3</button>
</div>
<div>
  <button id="4">4</button>
  <button id="5">5</button>
  <button id="6">6</button>
</div>
<div>
  <button id="7">7</button>
  <button id="8">8</button>
  <button id="9">9</button>
</div>
<div ><input type="submit" id='submit' value="submit"></div>

  • Related