Change the CSS of a table row when a link is in focus

Is there a way to style a <tr> element when an <a> tag inside of it is focused?

Below is the HTML for the table:

<table>
    <tr>
        <td>
            <a href"#" tabindex="1" accesskey="e">edit</a>
        </td>
    </tr>
</table>

When using the 'Tab' key, the link becomes selected. You can change the styling of the link using the following code:

a:focus {
    background: #CCC;
}

It's not possible to wrap the <tr> in an <a> tag due to having multiple links on one table row.
Are there any alternative solutions to achieve this?

Answer №1

Parent elements cannot be directly styled using CSS. Only child and sibling elements can be targeted with CSS.

To modify parent elements, you will need to utilize JavaScript.

Answer №2

This code snippet is designed to handle FOCUS events in both Firefox and Chrome browsers. The original poster did not specifically ask for mouseenter functionality.

Internet Explorer has known issues with jQuery focus... to learn more, visit JQuery focus() is not focusing in IE but it is in Chrome.

See this JSFiddle demo for handling FOCUS in FF / Chrome: http://jsfiddle.net/pmg45/2/

Here is the HTML snippet:

<table class="table">
<tr>
    <td>
        <a class="link" href"#" tabindex="1" accesskey="e">edit</a>
    </td>
</tr>
<tr>
    <td>
        <a class="link" href"#" tabindex="1" accesskey="e">edit</a>
    </td>
</tr>

The accompanying CSS style rules are as follows:

a { display:block; cursor:pointer; }
.red{ background:red; }

And here is the jQuery script that adds/removes a 'red' class upon focus/focusout of the link elements within a table row:

$(document).ready(function(e) {
    $('.link').on('focus', function(){
        $(this).parents('tr').addClass('red');  
    });
    $('.link').on('focusout', function(){
        $(this).parents('tr').removeClass('red');   
    });
});

Answer №3

For more insight, check out this helpful post on Stack Overflow: How to change `tr` style when an `input` is focused?

(Extracted from the above source)
You can achieve this by using a script that utilizes getElementByID to target and modify the desired row:

<html>
<head>
<script type="text/javascript>
function changeTrStyle()
{
document.getElementById("trId").style.background = "red";
}
</script>
</head>
<body>
<table>
    <tr id="trId">
        <td>
            <input type="text" onfocus="changeTrStyle()"/>
        </td>
    </tr>
</table>
</body>
</html>

Answer №4

To accomplish this task, utilize jquery and refer to the provided fiddle below:

http://jsfiddle.net/Mohinder/pmg45/

Here are the CSS styles:

a { display:block; cursor:pointer; }
    .red{ background:red; }

Include the following HTML code:

<table class="table">
    <tr>
        <td>
            <a class="link" href"#" tabindex="1" accesskey="e">edit</a>
        </td>
    </tr>
    <tr>
        <td>
            <a class="link" href"#" tabindex="1" accesskey="e">edit</a>
        </td>
    </tr>
</table>

Implement the jquery script as shown below:

$(document).ready(function(e) {
    $('.link').on('mouseenter', function(){
        $(this).parents('tr').addClass('red');  
    });
    $('.link').on('mouseleave', function(){
        $(this).parents('tr').removeClass('red');   
    });
});

Answer №5

Modifying the parent element in CSS when its child is affected by changes is not possible.

If you want to alter the parent element, you will need to utilize jQuery.

With jQuery, you can utilize the hover function to make changes to the parent element.

For instance:

$('a').hover(function(){
  $(this).parent().css({"color":"red"});
}); 

The code above demonstrates how to change the color of the immediate parent of a link when it is being hovered over.

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 PDF file cannot be displayed due to the dynamic loading of the path and filename

Currently, I am working on an AngularJS and Java application. The following HTML code is utilized to open a PDF file in the browser. However, there seems to be an issue where the PDF does not open when dynamically passing the value for the data attribute. ...

Issues with React Router server-side rendering: Error: Required prop 'history' was not specified in 'RoutingContext' prop validation

I am currently working on a fun little project to improve my React/Hapi skills and so far everything has been smooth sailing until I attempted to set up server-side routing. The server is running without any issues and successfully renders "/" with a simpl ...

Select DOM Elements Using JavaScript CSS Queries

As I delved into JavaScript in an attempt to craft my personal slider, I stumbled upon a perplexing discovery. I encountered a CSS regulation that looked like this: html.js #slideshow .slides img { position: absolute; } The explanation suggested that ...

Creating a PDF document with multiple pages using a PHP loop, integrating with AJAX, and utilizing the m

Looking for assistance with a plugin development project involving PDF generation using AJAX. The challenge lies in generating multiple PDFs for each user within a loop. The goal is to create PDFs with multiple pages for individual users. If that's n ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

Ways to conceal and reveal content within div elements

I have a code snippet that is currently operational, but I am looking to enhance it by displaying one div at a time. If you would like to view the code, please visit my CodePen link below: https://codepen.io/danongu/pen/YzXvpoJ Due to the extensive amou ...

Tips for deleting extraneous cells in a table without altering the placement of the other cells and refraining from employing CSS

I'm struggling with understanding how to merge cells in a table. Can someone explain the rules for merging table cells to me? I want to remove certain cells from the table without using CSS, I just want to make it look clean. <table border="1" ...

Using V-model binding in Vue always resets the content of text inputs

I am facing an issue with a Text Input that is filled based on a string stored in cookies, similar to a Remember me feature. When I bind the value of the input to the cookie using :value, I am unable to type a new value even if there is no cookie being sto ...

Ways to retrieve the selected option from a dropdown list

How can I extract the option value from a dynamically populated Select button in order to retrieve the necessary data from my database? I am unsure of how to obtain the value stored in the $giftName variable. I have attempted to use both jQuery and JavaS ...

What is the accurate way to write the ID selector for the select-option-selected in JQuery?

When it comes to extracting a value from a Select-Option using jQuery, the following syntax can be used. I have successfully retrieved data using this method. $( "#Vienna\\.rail0\\.track option:selected" ).text() However, there is an ...

Resolving issues with setting up d3.js in the 'Creating a Custom Map' guide

Starting Mike Bostock's tutorial on creating a map, but facing some installation issues at the beginning. I am using Windows 8.1 for this. This is the specific part that's causing trouble: "To get started, you'll need the reference implemen ...

The issue with ng-if not functioning within ng-repeat is that the ng-if directive

My issue is with using ng-if inside an ng-repeat in AngularJS. Despite updating to the latest version on 09/27/2014, I am still unable to make it work properly. The code functions perfectly outside of ng-repeat, and also works fine inside ng-repeat when us ...

While I believed that my template's if/else/endif logic would resolve the issue, I encountered a NoReverseMatch error when trying to access /

I received an error message as follows: NoReverseMatch for 'grouplocation_add' with arguments '('',)' not found. 1 pattern(s) tried: [u'ipaswdb/grouplocations/add/(?P<pk>[0-9]+)/$'] After adding context[&apos ...

Discover techniques for concealing the source code of AngularJS controllers on a web browser

Our current setup involves using angular JS with spring boot, and although everything is running smoothly, we are facing an issue regarding the separation of our UI deployment location from where the Java code resides. This has led to a situation where upo ...

Ways to prevent the Layout component from rendering on the NextJS login page

Is there a way to prevent the rendering of the Layout component in NextJS when the route is /login, /register, etc? const MyApp = ({ Component, pageProps }) => { return ( <Layout> <Component {...pageProps} /> </Layout> ...

Infinite scrolling feature on Kendo UI mobile listview showcasing a single item at a time

Currently, I am utilizing the kendo ui mobile listview and encountering an issue when setting endlessScroll or loadMore to true. The problem arises as the listview only displays the first item in such instances. Upon inspecting with Chrome inspector, I ob ...

What are alternative methods for adjusting the value of a CSS property with alternative parameters?

When it comes to using similarities in my code, I often find myself needing a more flexible solution. For example: .position{ position:absolute; right:10px; top:20px; } This is where the idea of using a mixin comes in handy: .position(@absolute:ab ...

JSX Transform error arises in Flask and Reactjs integration

Recently, I've delved into the world of ReactJS with a Python Flask Backend. While trying to render the template via Flask, Chrome Console shows this client error: Error: Cannot find module 'jstransform/visitors/es6-templates-visitors' ...

Obtain unique identifiers for the purpose of sorting the items

While utilizing Nuxt.js, I am fetching random images from URLs structured like this: http://www.randomimage.com?ID=myId To display 2 pictures, I use the following methods: getRandomArbitrary(min, max) { return this.numb = Math.floor(Math.random() * ...

The issue with color swapping in Internet Explorer is not functioning correctly due to

I am facing an issue with a jQuery script that I have created to change the background colors of rows in a large table. Unfortunately, it seems to be malfunctioning on Internet Explorer versions 6 through 9. Below is the snippet of code I am using: <s ...