Amir Mehrnam
Amir Mehrnam

Reputation: 550

How to set listener for elements that has same style value?

I want to set a listener for all elements that have same style value, that it can be setted any where in their style attribte, .css file or <header> style tag. After a lot of search I reach this code:

    $("body").on("click", '[style*="cursor:pointer"]', function (e) {
        const ripple = new Ripple();
        ripple.create(e, this.tagName.toLowerCase() == "a" ? 'dark' : 'light');
    });

But it's not working. I tried style~="pointer" and this did not work either. Both JS and JQuery are great for me.

Note: I found other related questions like using filter, so don't tell me it's duplicated and in my case, if I want to use filter to find elements with .css(), my listener has to be set for all elements in a page, that is not logical and optimized.

Upvotes: 0

Views: 79

Answers (1)

Tomas Korinek
Tomas Korinek

Reputation: 300

Unfortunately you cannot use CSS selector to get easily all elements by their style values. This works only for those which have the value set directly in their style html attribute.

The only way how to solve it by JS you already mentioned. That is the filter function, but you are right that it would not be efficient at all.

But maybe there are other ways how to fix this issue? Because it is actually quite rare to set some element behavior based on their css value. More common way would be to set it by class-name or tag-name.

So I do not know the context, but I would try one of these ways:

  1. If you are able to adjust HTML, set specific class to all the elements you want to target.
  2. If you cannot change HTML, you can try to create an array with several common attributes (tag-name, class-name) targeting your elements and based on it add the listener.

Upvotes: 2

Related Questions