If I have an HTML structure like:
<div id="name">
<div ><input id="first-name" type="text" /></div>
<div ><input id="last-name" type="text" /></div>
</div>
How do I target the last-name input field if the first-name input field has a certain class that is applied about user interaction?
For example, if a user clicks on the first-name input field, my JavaScript applies a "is-active" CSS class to it:
<div id="name">
<div ><input id="first-name" type="text" /></div>
<div ><input id="last-name" type="text" /></div>
</div>
I want to apply some CSS to the last-name field when that occurs.
I can't just do the following because the two input fields are not siblings.
input#first-name.is-active input#last-name { }
I've tried something like this:
.wrapper input#first-name.is-active .wrapper input#last-name { }
But that doesn't work. Any help would be greatly appreciated.
CodePudding user response:
What you want to do is not possible with current available CSS selectors as you've already noticed.
You can check if this :focus-within workaround would work for you (browser support is very good, with IE being the usual exception):
.wrapper:focus-within .wrapper > #last-name {
background: yellow;
}
<div id="name">
<div ><input id="first-name" type="text"></div>
<div ><input id="last-name" type="text"></div>
</div>
CodePudding user response:
You could also add a particular class using JS and apply some changes using css.
if ( document.querySelector("#first-name").classList.contains("is-active") ) {
document.querySelector("#last-name").classList.add("your-class");
} else {
document.querySelector("#last-name").classList.remove("your-class");
}
.your-class {
background-color: red;
}
<div id="name">
<div ><input id="first-name" type="text"></input></div>
<div ><input id="last-name" type="text"></input></div>
</div>
