3

How to make it work? HTML

#nav input[type=text]:focus ~ #two {
   color: red;
}
<div id=nav>
  <input type="text" placeholder="Search" name="search">
</div>
<div id="two">Two jfjsoijfoisoivnosnovdnsnnoivnoinsionvonoiniso</div>

I think the problem is due to the separate div elements.

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
Lessey
  • 35
  • 6

3 Answers3

2

#nav:focus-within ~ #two {
  color: red;
}
<div id="nav">
  <input type="text" placeholder="Search" name="search" />
</div>
<div id="two">Two jfjsoijfoisoivnosnovdnsnnoivnoinsionvonoiniso</div>

You can achieve this with :focus-within selector

Joshua
  • 3,055
  • 3
  • 22
  • 37
0

You can't. It's only possible if the element is a sibling or a child of the :focus.

Either use Javascript, or put put the div inside the nav (which might not be what you're looking for if you can't change your DOM tree).

#nav input[type=text]:focus~#two {
  color: red;
}
<div id=nav>
  <input type="text" placeholder="Search" name="search">
  <div id="two">Two jfjsoijfoisoivnosnovdnsnnoivnoinsionvonoiniso</div>
</div>

Pure Javascript :

var navbar = document.getElementById('nav')

navbar.addEventListener('focusin', toggleClass);
navbar.addEventListener('focusout', toggleClass);

function toggleClass() {
  document.querySelector('.two').classList.toggle('redColor');
}
.redColor {
  color: red;
}
<div id=nav>
  <input type="text" placeholder="Search" name="search">
</div>
<div class="two">Two jfjsoijfoisoivnosnovdnsnnoivnoinsionvonoiniso</div>
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
-1

Css can't parse Dom tree like jquery, So it can't parse parent element.

~ operator only work if your element exist in same depth.

<div id=nav>
    <input type="text" placeholder="Search" name="search">
    <div id="two">Two jfjsoijfoisoivnosnovdnsnnoivnoinsionvonoiniso</div>
</div>
Vicky P
  • 553
  • 6
  • 12