Score:0

How can I check if an element has a CSS class that matches a value in an array?

ru flag

In Drupal 9, I'm trying to check if an element has a certain css class using hasClass().

<p{{ attributes }}>Does this element have my css class?</p>

{% if attributes.hasClass('my-css-class') %}
  <p>Yes it does!</p>
{% else %}
  <p>No it doesn't.</p>
{% endif %}

Instead of checking for one class, I would like to check if my element has one of the classes contained in an array.

{%
  set my_css_classes = [
    'class-one',
    'class-two',
    'class-three'
  ]
%}

How can I check if my element has a class that matches one (or more) of the values in the my_css_classes array?

4uk4 avatar
cn flag
Loop over my_css_classes and check for each class?
Score:3
ve flag

Yeah, a simple loop should do:

{% set class_match = null %}

{% for class in my_css_classes %}
  {% if attributes.hasClass(class) %}
    {% set class_match = true %}
  {% endif %}
{% endfor %}

{% if class_match %}
  <p>Match exists</p>
{% endif %}
Tinto avatar
ru flag
Thank you @Prestoraurus! Works like a charm.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.