Home > OS >  not getting id value for classname on click in javascript
not getting id value for classname on click in javascript

Time:06-20

I am not getting id value for classname for list item on click in javascript. I am getting blank value.I just want to get id by any other method but don't want to get it through inline onclick method in html.

<ul >
   <li id="1" ><a ><i ></i>Orientation
      - chappter1.1-slide1</a>
   </li>
   <li id="2" ><a ><i ></i>Orientation
      - chappter1.1-slide2</a>
</ul>

var classname = document.getElementsByClassName("chapter-image");

for (var i = 0; i < classname.length; i  ) {

    classname[i].addEventListener('click', function () {
        var id = this.children[0].id;

        ///var attr = this.children[0].attributes['data-img-index'].nodeValue;
        openCard(id);
    });
}

CodePudding user response:

Try this,

window.onload = function() { const elements = document.getElementsByClassName('nameOfTheClass');

for (const element of elements) {
    element.addEventListener("click", e => {
        console.log("element was clicked", e.target.id, e.target.innerHTML);
    })
}

}

CodePudding user response:

use

id = classname[i].id

or

id = this.id

instead of

id = this.children[0].id

CodePudding user response:

You can simplified your code using onClick event in HTML.

<div onClick="openCard(1)" >chapter-image 1</div>
<div onClick="openCard(2)" >chapter-image 2</div>
<div onClick="openCard(3)" >chapter-image 3</div>

<script>
  const openCard = (cardId) => {
      alert(cardId)
  }
</script>

CodePudding user response:

I see, you hardcode the element index by 0. I think you mean

        var id = this.children[i].id;

The click event will cause bubbling, you need to check if the clicked element is the same element you want.

var classname = document.getElementsByClassName("chapter-image");

for (var i = 0; i < classname.length; i  ) {

    classname[i].addEventListener('click', function (event) {
      let id;
      if (event.target === classname[i]) {
        id = this.children[i].id;
      }

        ///var attr = this.children[0].attributes['data-img-index'].nodeValue;
        openCard(id);
    });
}

  • Related