PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to check if an element classList contains a string or word partially?

 July 08, 2022     class, contains, javascript     No comments   

Issue

I've got this code:

const all = document.querySelectorAll('div');
let variable = 'fruits';

all.forEach((item) => {
  if(item.classList.contains(variable)) {
   item.style.backgroundColor = 'red';
  }
});
<div class="fruits">
  Fruits
</div>

<div class="fruits-green">
  Green fruits
</div>

and I was wondering if theres to use classList.contains with a string/word partially?

Obviously what I'm trying to achieve is to get fruits-green styled too, since it contains fruits-green

I know there are CSS selectors for that, but given that my fruits variable will change with other JS functions, I'd like this to be vanilla JS too.

Any advice is much appreciated. Thanks!


Solution

The classList property is a DOMTokenList which is a string but has methods and properties simular to Array methods.

  • Iterate through the array of tags (all). We'll use .flatMap() because we are dealing with multiple tags that may or may not have multiple matches.
    all.flatMap((div, idx) => {//...
    
  • Next, we'll use the .value property of classList which returns a space delimited string of each of the tag's classes.
    let list = div.classList.value.split(' ');
    
  • Then we'll .filter() each class of each tag by comparing with .includes()
    list.filter(cls => cls.toLowerCase().includes('fruit'));
    
  • Finally, an array of arrays is returned. Each sub-array contains a tag's matching classes.
    const all = Array.from(document.querySelectorAll('div'));
    
    let output = all.flatMap((div, idx) => {
      let list = div.classList.value.split(' ');
      console.log(list)
      let matches = list.filter(cls => cls.toLowerCase().includes('fruit'));
      return [matches];
    })
    
    console.log(output);
    <div class="fruits fries">
      Fruits fries
    </div>
    
    <div class="fruits-green fruity">
      Green fruits fruit
    </div>


Answered By - zer00ne
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing