-4

How to click on the pseudo Element using jQuery I'm unable to click on before element to change the background color:

$(".box:before").on('click',function(){
    (".box h1").css("background-color","red");
    });
.box:before{
    content:"";
    width:10px;
    height:10px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
    <h1>hello</h1>
    </div>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Anand
  • 207
  • 2
  • 8

1 Answers1

1

First of all you've missed the $ sign in this instruction:

  (".box h1").css("background-color","red");

Then you can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

SOURCE: Access the css “:after” selector with jQuery

Please check & run the following code snippet for an alternative solution:

$(".box").on('click',function(){
    $(".box h1").css("background-color","red");
    });
.box:before{
    content:"";
    width:10px;
    height:10px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
    <h1>hello</h1>
    </div>
Mehdi Bouzidi
  • 1,937
  • 3
  • 15
  • 31
  • wrong, you better know about .before() before making this answer. See http://api.jquery.com/before/ – vnt Sep 22 '17 at 18:37