What is the best way to retrieve all classes that have a hyphen/dash in them from a DOM element and then store them in an array using JavaScript?

How can I retrieve all classes that contain a hyphen/dash applied to any DOM element and store them in an array using JavaScript?

My current approach:

const getClasses = [];
const classesContain = [];

document.querySelectorAll('*').forEach(element => {
    const classNames = element.className.split(' ');
    getClasses.push(classNames);
});

getClasses.forEach(classArray => {
    if (classArray.includes('-')) {
        classesContain.push(classArray);
    }
});

Answer №1

It seems like you're on the right track with your solution, but there are a few tweaks needed to make it work properly. Instead of pushing an array into the getClasses function, you should be passing individual classes. Remember that neither strings nor arrays have a standard contains method; you may want to use includes instead.

let classesWithDashes = new Set();
document.querySelectorAll('*').forEach(element => { 
  for (const cls of element.className.split(' ').filter(name => name.includes("-"))) {
      classesWithDashes.add(cls);
  }
});
// Now, `classesWithDashes` contains all the class names with dashes
// If you need them in an array format:
classesWithDashes = [...classesWithDashes];

Here's a demonstration:

let classesWithDashes = new Set();
document.querySelectorAll('*').forEach(element => { 
  for (const cls of element.className.split(' ').filter(name => name.includes("-"))) {
      classesWithDashes.add(cls);
  }
});
// `classesWithDashes` now holds the classes with dashes
// Convert to an array if needed:
classesWithDashes = [...classesWithDashes];
console.log(classesWithDashes);
<div class="foo foo-bar"></div>
<div class="another-one"></div>
<div class="no-dash-class"></div>


(I've always wondered why Set doesn't include something like an addAll method or allow multiple values to be passed to add, similar to push...)

Answer №2

Retrieve all elements with a class containing a hyphen by using document.querySelectorAll() along with an attribute selector. Transform the results into an array using Array.from(). Proceed to iterate through the elements using Array.flatMap(), extract the classlist, convert it to an array, and filter out classes that lack a hyphen. Utilize a Set to eliminate duplicate items and then spread them back into an array.

const result = [...new Set( // employing a Set for unique item collection
  Array.from(document.querySelectorAll('[class*="-"]')) // choosing elements with hyphen-containing classes
  
  .flatMap(el => Array.from(el.classList).filter(c => c.includes('-'))) // generating an array of classes with hyphens
)]

console.log(result)
<div class="something a-b something-else x-y"></div>
<div class="something"></div>
<div class="a-b c-d"></div>

Answer №3

It's important to note that by pushing an array of classes into your getClasses array, you are actually creating a 2-dimensional array.

Furthermore, you can streamline the process by extracting and filtering classes containing dashes in one single step, instead of going through the list twice.

var classesContain = [];

document.querySelectorAll('*').forEach(x => {
  var y = (x.className || '').split(/\s+/g); // using a regex to handle multiple spaces
  y.forEach(className => {
    if (className.includes('-'))
      classesContain.push(className);
  });
});

console.log('Final class list: ', classesContain);
<div class="foo-bar bar-baz foo">
  <div class="foo-baz">
    <span class="single">Example markup</span>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to make multiple requests in node.js using npm and then wait for all of them to finish

I am currently working on a program that needs to make 3 separate requests to 3 different URLs. The issue I'm facing is that the program takes about 1.5 seconds to run through all 3 requests because it waits for each request to complete before moving ...

Spin the content of a div after a button click with the power of jquery and css

Looking to add interactivity to rotate text within a div upon button click using jQuery and CSS. If the user selects Rotate Left, the text will rotate to the left. Alternatively, if the user chooses Rotate Right, the text will rotate to the right. Here&a ...

Having difficulty updating the login button name with ng-show function

Once a user logs in, I set a boolean value to true and intend to update the login button status to display "Logout". Despite attempting to use ng-show, the functionality does not seem to be working properly. App States: myApp.config(function ($stateProvi ...

Troubleshooting the challenge of saving multiple records using ajax in Django

Having trouble saving my form multiple times? I want users to be able to fill out the form with as many dimensions as needed. For example, if they enter two dimensions, I want to save each one as a separate record in the database. Any guidance on how to ac ...

Attempting to save an image captured in a Vue form and then transmit it to the Laravel backend

Hey everyone, I'm a newcomer to Vue and Laravel and I'm currently working on a REST project. I have a form that allows users to upload an image, but I keep encountering an error when trying to store it in the database: "Request failed with ...

Toggling the JQuery toggleClass() function to switch a class on and off (or delete it afterwards

Utilizing an angular directive to display a page with left and right columns using <left-column></left-column> and <right-column></right-column>. Whenever a user clicks on an anchor tag <a href="#target1">Target 1</a>, i ...

sophisticated HTML navigation bar

I am looking for a way to create a menu where the drop-down items overlay the rest of the menu when the screen width is small. Here is my current code: nav{ line-height:100%; opacity:.9; }nav ul{ background: #999; padding: 0px; border-radius: 20px; ...

React: I am looking to incorporate two API calls within a single function

I am currently learning ReactJS and focusing on implementing pagination. My goal is to fetch page data from a server using an API, with Loopback being the tool for API integration. The initial setup involves displaying a list of 10 entries on the first pag ...

What is the best way to locate all complete words within a string, up to 65 characters in length?

Looking to enhance my titles for better Google SEO (using title tag in html). My product titles are currently 3-4 lines long and do not look appealing. I am looking for a way to identify the last complete word before the 65th character in a string. For e ...

Transitioning from the login screen to the main page in Ionic with the help of Angular

My code is running smoothly, but I encountered an issue when clicking the login button. It changes the state as depicted in the image, altering the URL but failing to open the subsequent page. Can anyone provide guidance on how to redirect to the next page ...

Fade in background color with jquery when scrolling

Is there a way to make the header background fade in after scrolling a certain number of pixels? The code I have sort of works, but not quite right. Any suggestions? Thank you! $(function () { $(window).scroll(function () { $(document).scrol ...

How can I display actual images received as escaped string literals from ExpressJS?

Is there a way to transform this data from ExpressJS into an actual image? The information I'm receiving looks like this instead of an image: {`data: 'PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\ ...

Can you explain how the functionality of setState operates within React in this specific situation?

I've been working on updating the state of an object in my array. I managed to get it done, but I'm a bit confused about how it works. toggleVisited = countryCode => { var countries = [ ...this.state.countries ]; var countryToChange = c ...

What is the best way to automatically show the last two digits of a phone number in a second text field?

Is there a way to automatically display the last 2 digits of a phone number input into the first text field onto the second text field using AJAX, JavaScript, or jQuery? I am looking for a script for my website similar to what was shown in this video. I ...

Exporting variables in node.js allows you to share data between different

Hi, I'm currently working with a file that looks like this: module.exports = { some variables that are being exported here, execute(message) { } } I want to export the message parameter to another file. I've attempted using var msg ...

NodeJs: Transforming strings into UUID v4 efficiently

Suppose I have the following string: const input = '83e54feeeb444c7484b3c7a81b5ba2fd'; I want to transform it into a UUID v4 format as shown below: 83e54fee-eb44-4c74-84b3-c7a81b5ba2fd My current approach involves using a custom function: funct ...

Utilizing a function as an argument in another function (with specified parameters)

I’m stuck and can’t seem to solve this problem. In my function, the parameter filter needs to be a function call that accepts an object created within the same function: function bindSlider(time, filter) { var values = { min : 8, max : ...

When using Vue.js, styling SVGs with CSS proves difficult as it applies inline styles in the DOM rather than using class names

Recently, I tried to update the appearance of some SVG images using CSS, but to my surprise, nothing changed. Upon inspecting the page, I noticed that the styles were located under the 'element.style' tag, which may explain why my attempts were u ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

Extracting data from an array using Angular

Currently, I am developing an Angular application that involves handling an array structured like the one below. [ { Code: "123", Details:[ { Id: "1", Name: "Gary" }, { ...