Home > Blockchain >  JavaScript click to get specific value from same class name
JavaScript click to get specific value from same class name

Time:10-12

I'm very new to JavaScript and I have a html like this:

<li><a  href="#">wtdata</a></li>
<li><a  href="#">ftdata</a></li>

Is there anyway after clicking each link ,I can get the specific text of the link, without adding id for them.for example ,if I click the first link ,then I get the text wtdata,if I click the second link ,I get the text ftdata.

I'm using JavaScript not jQuery.

I have tried:

 <li><a onclick="getValue(evt)"  href="#">wtdata</a></li>
 <li><a onclick="getValue(evt)"  href="#">ftdata</a></li>

  <script>
    function getValue(evt) {
      alert($(evt.target).text());
}
  </script>

But it not work.

CodePudding user response:

For pure javascript:

  1. Add addEventListener (click)
  2. user this.innerHTML to get the value
  3. use an alert to display the value (or use other JS function to do what you want)
<li><a  href="#">wtdata</a></li>
<li><a  href="#">ftdata</a></li>


<script>

var myFunction = function() {
    var attribute = this.innerHTML;
    alert(attribute);
};

var elements = document.getElementsByClassName("dropdown-item");

for (var i = 0; i < elements.length; i  ) {
    elements[i].addEventListener('click', myFunction, false);
}

</script>
  • Related