How to call the same jQuery function when clicking elements that have the same identifiers

I have many elements that have the same thing, but with different data, I want to call the same JQuery function when I click on each element. How can i do this?

+3
source share
4 answers

You cannot have multiple identifiers in your HTML markup.

This will be the wrong markup. When querying for $('#foobar')and there are five elements that have this id, you will only get the first instance. Therefore, even if there was a way (...) to apply the code to all these nodes, do not do this.

Use Classnames when you want to "combine" some elements.

+8
source

. .

<div class="myClass">..</div>
<div class="myClass">..</div>

$(".myClass").click(function() {...});
+6

jQuery ("div,span,p.myClass").click(function() {

//your code
});

+1

When working with an identifier can create a lot of redundancy, it is better to work with classes, but if your classes will be repeated, and maybe a little difficult to handle, I would recommend that you use some custom attributes for this

Sample code for you.

    var spnActive = document.createElement("span");
    $(spnActive).attr('isExpColSpan', 'true');
    $('#dvContainer').find('span[isExpColSpan="true"]').

In the second line, I added a custom attribute in the next line. I showed how to use this attribute.

0
source

All Articles