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
  • 5,806
  • 4
  • 14
  • 32
Lessey
  • 35
  • 5

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

konekoya
  • 2,439
  • 2
  • 21
  • 34
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,357
  • 6
  • 25
  • 53
-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
  • 405
  • 3
  • 11