Emphasize the selected item using the same style as the one that was dragged or clicked

Imagine a scenario where there are numerous items, each labeled with a specific class. There may be multiple items sharing the same class.

If a user clicks or drags an item, I want all other items with the same class to be highlighted as well.

I am looking for a more sophisticated approach rather than simply using JavaScript to loop through all items and apply the "highlighted" class to matching items.

Is there a way to achieve this without needing to manually define or generate CSS for each class?

Answer №1

This code snippet provides a solution that dynamically injects styles based on the selected class. By utilizing a CSS attribute selector and child selector, it is able to apply highlighting to the elements.

const divs = document.querySelectorAll(".outer > div");

Array.from(divs).forEach((element, index) => {
  element.addEventListener("click", (e) => {
    e.stopPropagation()
    const selectedClass = element.className;
    document.querySelector(".outer").dataset.selected = selectedClass;
    document.body.appendChild(Object.assign(document.createElement("style"), {
      textContent: `[data-selected=${selectedClass}] .${selectedClass} {background-color: yellow}`
    }));
  });
});
.outer > div { cursor: pointer; }
<div class="outer">
  <div class="apples">apples</div>
  <div class="birds">birds</div>
  <div>No class</div>
  <div class="apples">apples</div>
  <div class="birds">birds</div>
  <div class="pines">pines</div>
  <div class="pines">pines</div>
  <div class="birds">birds</div>
</div>

Answer №2

It may not be possible to achieve the exact functionality as described, but you can utilize :focus-within to achieve something similar:

.main:focus-within .a {  
  background: red;
}

.a,
.b {
  width: 100px;
  height: 100px;
}

.a {
  background: yellow;
}

.b {
  background: blue;
}
<div class="main">
  <button class="a"></button>
  <button class="b"></button>
  <button class="a"></button>
  <button class="b"></button>
  <button class="a"></button>
  <button class="b"></button>
</div>

One drawback is that when focusing on a .b element, .a elements will also have a red background. Additionally, this method requires using focusable elements.

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

The Art of Unraveling a String in SQL Server

Could someone please advise on the most effective method to convert special characters in a string back to their normal form using HTML decoding? ...

Why does my PHP script execute before receiving any input?

As a newcomer to PHP from C#, I am currently developing a whois module for a website. However, I'm encountering an issue where my PHP page automatically runs and displays the message "invalid input" before I even click the button. Can anyone explain w ...

Scoped Styles rarely stand a chance against more dominant styles

I'm facing a scope issue while learning Vue. Question: I am trying to make sure that the styles in profile.vue do not override the ones in sidebar.vue. I want the sidebar to have a red background and the profile section to be blue. Shouldn't usi ...

The menu seems to be off-center

I'm struggling to center my menu/navigation bar horizontally. I can't seem to figure out what mistake I've made or what I've forgotten. Additionally, there is right padding after my last list item. How can I get rid of it? HTML <di ...

What is the best way to update the text of an <a> element when it is clicked

On my WordPress site, I've implemented a unique custom anchor button: <a class="add-to-cart-button">Buy Now</a> I'm interested in making the button text change when it's clicked. Could this functionality be achieved using java ...

Tips for disabling default browser input validation in React

https://i.stack.imgur.com/834LB.png Is there a way to remove the message "Please fill out this field" while still keeping the "required" attribute intact? I have my own validation system in place, so I need to use the "required" attribute to determine whe ...

What could be preventing my PHP function from being executed when the button is clicked?

My PHP block has all the working get functions as expected. <?php function getTitle() { $connection = new PDO('mysql:host=x.x.x.x;dbname=x;charset=utf8', 'x', 'xxxx'); $query = $connection->query("SELE ...

``There is a need to modify the content within various if

I have a project where I need to update multiple iframes with different content from an array, for example: <ul> <li> <iframe src="test.html"> <head></head> <body> <div class="content"> ...

When an absolute positioned element exceeds the right border of its relative parent, its width will be truncated

When position: absolute; divs are placed inside or around a position: relative; parent, their height and width are based on the size and length of the text they contain. However, if one of these divs extends beyond the right border of the relative parent, ...

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

Allowing users to navigate through a fixed content page using a scrolling menu, all without the need

On my webpage, I have integrated Google Maps. The layout is divided into a menu on the left and content on the right. I am looking to make the left side (menu) scrollable, while the right side (content, which includes the map) remains static without scrol ...

What is the best way to align isotope and organize its components?

I have searched for solutions to my issue with centering isotope on my project, but none of the existing answers were sufficient. I am facing challenges trying to center isotope without creating extra space between its elements and arranging them in a spec ...

Submitting data through AJAX when clicking a button

I am currently troubleshooting the behavior of my ajax code when I submit it. Most of the elements in my form have onchange="mySubmit(this.form)" or onclick="mySubmit(this.form)" to trigger the ajax submission, and this works well for input elements where ...

Is there a different option to use instead of embedding two forms?

I'm currently facing an issue and seeking alternatives for it. In my admin panel, customers have the ability to manage buildings by adding, editing, or deleting them. I have a form with fields such as title, address, city, etc., along with a submit ...

Having trouble with my PHP index not properly redirecting to the dashboard file after logging in

I have created a login form and implemented some functionalities. One of the key features is redirecting to the dashboard file after successful password validation. I attempted to troubleshoot using chatgpt, but the issue persists. I am reaching out for as ...

How come this bootstrap text starts overlapping the image when I resize the screen?

In my Bootstrap 5.1 project with a fluid container, I have a row with two columns - one with a width of 3 and the other with a width of 9. Everything looks fine when the screen is fullscreen: https://example.com/image1.png However, when I resize the win ...

What are some ways to add border styles to the Material UI TableRow Component?

In my project, I am utilizing the Table component from Material UI. I have been trying to apply border styles to the TableRow Component using scss classNames for styling purposes. Usually, the border styling is applied in the TableCell, but this doesn&apos ...

Highlight the menu when the user is actively browsing this section

I have successfully implemented a fixed and sticky menu with a progress bar that resembles an underline. However, I am facing an issue with positioning the progress bar correctly under each menu section. For example, when a user hovers over the first secti ...

Retrieving script data from a webpage

I found a link that I want to extract content from, here is the link: https://www.whatever.com/getDescModuleAjax.htm?productId=32663684002&t=1478698394335 However, when I try to open it using Selenium, it doesn't work. It opens as plain text wit ...

Issue with PageSpeed and Lighthouse showing NOT_HTML error post recent update

Our team decided to utilize the tool at for assessing the speed of our website. This tool has been effective in analyzing our site's URLs for some time now. However, recently we have encountered an issue where we receive the following error message: ...