0

In the below code, I try to display content: text with jquery.

If I delete :before it works! Why doesn't jQuery allow that while javascript do that.

This post (7 years ago) talks about my problem, but it works around the problem without giving a simple solution.

Today there is no simple solution to target :before?

thanks for your help

$(document).ready(function() {
  $("div").mouseenter(function() {
    $("li:nth-child(2):before").show();
  });
  $("div").mouseleave(function() {
    $("li:nth-child(2):before").hide();
  });
});
li {
  display: none;
}

li:before {
  content: 'Show me';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>This is a paragraph.</li>
  <li>This is a second paragraph.</li>
</ul>

<div style="width:30px; height:30px; background:black;cursor:pointer;position:absolute; top:50px;"></div>
Pete
  • 57,112
  • 28
  • 117
  • 166
Rak Arthus
  • 17
  • 6

1 Answers1

0

The pseudo-element's visibility depends on the visibility (i.e. display status) of its main element, the li:nth-child(2). So you have to add an according line in your jQuery functions to also show/hide the main element:

$(document).ready(function(){
    $("div").mouseenter(function(){
        $("li:nth-child(2)").show();
        $("li:nth-child(2):before").show();
    });
    $("div").mouseleave(function(){
        $("li:nth-child(2)").hide();
        $("li:nth-child(2):before").hide();
    });
});
li{display:none;}
li:before{content:'Show me';}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>
<ul>
<li>This is a paragraph.</li>
<li>This is a second paragraph.</li>
</ul>

<div style="width:30px; height:30px; background:black;cursor:pointer;position:absolute; top:50px;"></div>


</body>
</html>
Johannes
  • 64,305
  • 18
  • 73
  • 130