Is it possible for CSS hover to have an impact on multiple divs that share the same class name

There are 5 divs on the page, all with the same class name as shown below:

Here is the CSS:

.test:hover{
   color:red;
}

And here is the HTML:

<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

Now, imagine these divs are in different parent divs on the page...

The goal is for all 5 divs to change to red when hovering over any of them, not just the one being hovered over...

Unfortunately, they do not share the same parents, so I can't wrap them in a parent div and use a hover effect. Is there a way to achieve this using CSS, or will I need to resort to JavaScript?

Answer №1

An effective vanilla JavaScript method that can be utilized in compliant browsers supporting `[].forEach()` and `document.querySelectorAll()`, especially when CSS is unable to perform the intended task, involves the following code snippet:

function toggleClass (event, classNameToFind, classNameToToggle) {
    [].forEach.call(document.querySelectorAll('.' + classNameToFind), function(element){
        element.classList[event.type === 'mouseover' ? 'add' : 'remove'](classNameToToggle);
    });
}

var elements = document.querySelectorAll('.test');

for (var index = 0, length = elements.length; index < length; index++){
    elements[index].addEventListener('mouseover', function(event){
        toggleClass(event, 'test', 'highlight');
    });
    elements[index].addEventListener('mouseout', function(event){
        toggleClass(event, 'test', 'highlight');
    });
}

Check out the JS Fiddle demo for a demonstration.

For further reading:

Answer №2

If you're looking to achieve a specific effect, using JQuery can simplify the process. You can try copying the code below into an .html file for testing:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script>
        $(document).ready(function() {
            $(".test").hover(
              function() {
                $(".test").css("background-color", "red");
              }, function() {
                $(".test").css("background-color", "");
              }
            );
        });
        </script>
    </head>
    <body>
        <div class="test">My Div</div><br />
        <div class="test">My Div</div><br />
        <div class="test">My Div</div><br />
        <div class="test">My Div</div><br />
        <div class="test">My Div</div>
    </body>
</html>

Answer №3

In current times, CSS does not provide a way to target an element's parent directly. This restriction also applies when attempting to select an element based on its parent. It serves as a little demonstration of the limitations of CSS.

Answer №4

Take a look at this provided code snippet:

css:

.example{
background: none repeat scroll 0 0 #FFFFFF;
height: 105px;
opacity: 0.1;
position: absolute;
top: 0;
width: 5%;
}
.example:hover ~ div{
color:red;
cursor:pointer;
}

html:

<div class="example"></div>
<div class="container">
  <div class="test">1111</div>
</div>
<div class="container">
  <div class="test">2222</div>
</div>
<div class="container">
  <div class="test">3333</div>
</div>
<div class="container">
  <div class="test">4444</div>
</div>
<div class="container">
  <div class="test">5555</div>
</div>

Explore the live demonstration via this link: http://jsfiddle.net/eN49z/

Answer №5

Unfortunately, achieving the desired effect using CSS alone is not possible. CSS is limited to affecting elements downwards in the DOM tree and cannot travel upwards to affect parent elements.

However, by utilizing JavaScript, specifically with jQuery in this example, you can achieve the desired effect. The method used to target other <div> elements with the class test may vary depending on the nesting structure and relationships among elements.

Here is a sample markup illustrating the situation:

<div>
    Parent 1
    <div class="test"></div>
</div>
<div>
    Parent 2
    <div class="test"></div>
</div>
<div>
    Parent 3
    <div class="test"></div>
</div>

The CSS code is straightforward. The .hover class is dynamically added by jQuery, not using the :hover state:

.test:hover, .test.hover {
    background-color: red;
}

The JavaScript code might look something like this:

$(function() {
    $(".test").hover(function() {
        // Find '.test' in all siblings of the parent containing '.test'
        $(this).parent().siblings().find(".test").addClass("hover");
    }, function() {
        // Additional criteria can be applied to select specific '.test' elements
        $(document).find(".test").removeClass("hover");
    });
});

http://jsfiddle.net/teddyrised/fHwFf/

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

Why do all the select boxes require two clicks to open the drop-down menu when the function is activated?

After implementing this code on my webpage, I noticed an issue where all select boxes required two clicks from the user to open the drop-down menu. The first click seemed to set focus on the box, and only on the second click would the drop-down actually ap ...

Guide to setting up the primary navigation in the WordPress administration panel

I recently started using WordPress and I'm struggling with changing the main menu href category. I've tried looking for the header in the FTP files, but I still can't figure out how to do it. I've read through all of the WordPress help ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

What is the reason behind the change in style hierarchy when using ':last-child'?

I found myself in a confusing situation where using :last-child is affecting how parent classes are being applied. The task at hand is to style the last element in a list of elements. However, upon using :last-child, the priority of styles shifts and one ...

Form fields in Bootstrap 4 will consistently expand downward in the select dropdown menu

When using bootstrap 4, I want my field to always expand downwards and never upwards, even when half the screen is taken up by the form's select element. How can I achieve this effect? I have tried using data-dropup-auto="false" but it didn't wo ...

"Trouble with Bootstrap 4 menu: only one dropdown opens at a time

I am facing an issue where the text remains a link and the dropdown toggle works, but it is causing Dropdown-2 to open when I click on Dropdown-1. Only Dropdown-1 seems to be working properly. I can't seem to figure out why only Dropdown-1 opens no m ...

The line segment refuses to remain hidden beneath the h2 tag

Just getting started with HTML/CSS here! I'm trying to figure out how to keep a line directly under an h2 tag. In my code, there's an h2 tag labeled 'Instructions' followed by a div containing 3 other divs making up a line segment. By d ...

Can an unordered list be nested inside an inline list item in HTML or XHTML?

Take note that the li with child ul is set to display:inline - example code provided below <style type="text/css"> ul.nav_main li { display: inline } ul.nav_submenu li { display: block } </style> <ul class="nav_main"> <li>I ...

Utilizing React to Style Background Positions

I've been struggling to position a block of rendered jsx on the right side of the first block for hours now. Despite trying various options like marginTop, marginLeft, and even backgroundPosition based on my research, I still haven't been success ...

Prevent keypress from being detected while the confirm box is displayed

My website heavily relies on key events, and for certain actions, it triggers a bootbox confirm box. This confirm box appears over a transparent layer, blocking all mouse click actions unless the user interacts with the confirm box. Now, I also want to dis ...

Tap on the screen to initiate a phone call using dompdf

I recently came across a recommendation to include the following code snippet to enable click-to-call functionality: <a href="tel:555-555-5555">555-555-5555</a> However, I encountered an issue when trying to implement this in dompdf. ...

How can I properly integrate jQuery libraries, along with CSS, in a create-react-app project?

I'm currently working on incorporating the select2 jquery library into my React application, which was created using create-react-app. After adding jquery and select2 to my package.json file, I was able to get the javascript functionality to work pro ...

Toggle button color on click by using ng-click on a different button

As a newcomer to Angular, I am facing an issue. I have two buttons - button1 and button2. What I want is that when I click on button1, its color changes from green to red. Then, when I click on button2, the color of button1 should revert back to green. How ...

The browser is capable of detecting multiple key presses using JavaScript

I'm attempting to trigger an action when certain keys are pressed simultaneously. The keys I need to detect are bltzr, but my browser only registers bltz without the final r. I've tried this on both Windows and OSX, but still can't capture ...

The vue template is indicating an error related to unused variables according to the eslint rule vue/no

Perhaps this information will come in handy for someone. I am working with a Vue template that contains HTML. <template slot="HEAD_Status" slot-scope="data"> <!-- some html without using of data --> </template> Eslint is showing [v ...

Perform an Ajax request with JQuery in an HTML document and transfer the response to a different HTML page

This is my first attempt at using AJAX and jQuery to retrieve data from another HTML page. Below is the code I have written: Here is my JavaScript code: <script type="text/javascript> $(document).ready(function() { $('#submit').click( ...

`Set the body height to equal that of the entire document`

Currently facing an issue on the test page when scrolling down: The body element is set to have a height of 100%, but it only takes up the viewport's height, not the entire document height. The goal is for the page to always display at 100% of the d ...

What is the best way to ensure a div container fills the entire height of the screen?

I am currently working on developing my very first iOS HTML5 app, which is a simple quote application. One challenge I am facing is how to set the height of my container div to match that of an iPhone screen. You can view the design I have so far on this j ...

what is the best way to change background image in media query for various screen sizes?

I have a customized email template with a background image. The size of the image is 600px (width), and I have applied a class called back-img for styling purposes. I am looking to override this class specifically for all mobile screen sizes, including lan ...

Creating a dropdown navigation menu using CSS from href divs

I am working on a script that includes divs with images and href functions for clicking on them. <div class="home"><a href="index.php?pagina=home"></a></div> <div class="events"><a href="index.php?pagina=events"></a& ...