LoginSignup
59
53

More than 5 years have passed since last update.

:afterなどのCSS擬似要素のStyleを動的に変更する

Posted at

通常は下記のようにcssプロパティによってStyleを指定できる。

$('#hoge').css('color', 'red');

しかし、jQueryで:afterなどの擬似要素にはセレクタでアクセスすることができない。(非DOMであるため)
ボタンクリックのタイミングなどで、擬似要素のStyleを変更したい場合は下記のように動的にstyleタグを生成して書き換えると上手くいく。

<html>
  <head>
    <style id='foo' type='text/css'></style>
    <style type='text/css'>
      #hoge:after {
        content:"E";
      }
    </style>
  </head>
  <body>
    <div>
      AB<span id='hoge'>CD</span>F
    </div>
    <button id="btn" type="button" value="Button">
  </body>
</html>
var cssTemplate = '<style type="text/css">#hoge:after{color: #[color_code];}</style>';

$('#btn').on('click', function(e){
  var css = cssTemplate.replace('#[color_code]', 'red');
  $('#foo').replaceWith($(css));
});

59
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
59
53