0

I have a simple script for animate. Its only one animate on web, so I want use only Javascript without Jquery for easy of it.

I have script:

var btn = document.getElementById("myBtn");

btn.onclick = function() {
    modal.style.display = "block";
}

But I want use it on class and I need their id:

<a class="button" id="first"></a>
<a class="button" id="second"></a>

In Jquery I can write:

$('a.button').click(function() {
            myId = $this.id();
            ...
            modal.style.display = "block";

});

How I can write it in Javascript?

Thanks!

PS: Sorry for my English :-)

Joe
  • 1
  • 1
  • `document.querySelector/All()` lets you use the same CSS selectors jQuery uses. – Sterling Archer Feb 12 '18 at 22:28
  • Possible duplicate of [How to get element by class name?](https://stackoverflow.com/questions/17965956/how-to-get-element-by-class-name) – Striped Feb 12 '18 at 22:29
  • When you receive an event via the click handler, you can refer to the element on the page via [`event.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target) – jpaugh Feb 12 '18 at 22:30
  • @Striped Probably not. The OP needs to know which element fired the event before looking it up. – jpaugh Feb 12 '18 at 22:31
  • @Joe I believe the answer to [this question](https://stackoverflow.com/q/4358067/712526) shows what you need. If so, please mention it, so we can close this question. If not, please clarify what you actually need. Thanks! – jpaugh Feb 12 '18 at 22:33
  • @Joe Could Are you looking for `this.className` ? https://stackoverflow.com/questions/17060971/get-class-name-from-element-with-onclick – Striped Feb 12 '18 at 22:35

1 Answers1

0

you can do it like this:

 <a class="btn" id="btn1" href="#">Button 1</a>
 <a class="btn" id="btn2" href="#">Button 2</a>
 <script type="text/javascript">
     // Get all the elements of the 'btn' class
     // Code below returns an array
     var btnElements = document.getElementsByClassName("btn");
     var len = btnElements.length;
     while(len--) {
         // Iterate on each element
         var btn = btnElements[len];
         // Attach click event for each element
         btn.onclick = function(e) {
             // Get the id property of clicked element
             var id = e.target.id;
             // More code here
         };
     }
 </script>
CodeLover
  • 571
  • 2
  • 11