Theme colour switcher

JavaScript function to find a class on an element containing a particular string

Just plopping this here for future reference and in case it might be useful to someone.

I'm having to work with a platform which shall remain unnamed but whose code makes working with it very difficult. Among other things, it gives form elements unique classes with ID numbers, but for some reason no IDs. So I needed to filter the class list to find the unique class so I can set the element's ID to that string, in order to programmatically associate form descriptions with their inputs, for accessibility.

// This is within a forEach function which loops over the "section" elements
// we have to spread each section's class list into an array. You can also use Array.from
// we then filter each item in the class list array to find the one which contains the string "-id-". Obviously this can be any string you need to find

const uniqueClass = [...section.classList].filter((item) => item.includes('-id-'));

Tags:

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.