1

Is it possible to bind events to multiple elements in HTML without using components.

Ex:

<ul>
  <li>
  <li>
  <li>
  <li>
</ul>

So can I bind a click events to all those <li> elements. If yes, how?

1 Answer 1

6

You can use event delegation. Since events bubble up, you can put a click handler on the ul element and it will fire for a click on any of the contained lis. In the event object, target indicates on which element the event triggered, and currentTargetindicates the element the handler is attached to.

new Vue({
  el: 'body',
  methods: {
    something: function(event) {
      console.log('Clicked:', event.target.textContent);
      console.log('Binding is on:', event.currentTarget);
    }
  }
});
ul {
  cursor: pointer;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<ul @click="something">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

Sign up to request clarification or add additional context in comments.

4 Comments

how to create a functionality for every " li " tag? like: event.target.eventListener(...) ?
@sina You could put @click on each <li>. But I'm not sure I understand what you're asking.
Is it possible to add EventListener to all elements selected by getElementsByClass() ? My component gets a HTML from a external service and doesnt know markup structure in advance.
@AviMehenwal For events that bubble, you can put the listener on the element that contains all the elements (body, perhaps) and in the handler check that the element being fired on is one of the set. Or you could iterate the set and put a listener on each item.

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.