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 :-)

6
  • document.querySelector/All() lets you use the same CSS selectors jQuery uses. Commented Feb 12, 2018 at 22:28
  • Possible duplicate of How to get element by class name? Commented Feb 12, 2018 at 22:29
  • When you receive an event via the click handler, you can refer to the element on the page via event.target Commented Feb 12, 2018 at 22:30
  • @Striped Probably not. The OP needs to know which element fired the event before looking it up. Commented Feb 12, 2018 at 22:31
  • @Joe I believe the answer to this question shows what you need. If so, please mention it, so we can close this question. If not, please clarify what you actually need. Thanks! Commented Feb 12, 2018 at 22:33

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.