jquery !importantを付けてcssを変更する

jquery !importantを付けてcssを変更する

jqueryでcssメソッドを使用して、!importantを付けてcssを変更するための手順を記述してます。

環境

  • OS windows10 pro 64bit
  • jquery 3.5.1

!importantをつける

cssメソッドを利用したサンプルとなります。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>サンプル</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script>
  $(function() { 
    $("#btn1").click(function() {
      //margin変更
      $("#sample").css({'cssText': 'margin-top: 100px !important;'})
    });
  });
  </script>
</head>
<body>
  <div class="jumbotron">
    <h1 id="sample" class="display-4">Hello, world!</h1>
    <p class="lead">ID sampleのmarginを変更します。</p>
    <hr class="my-4">
    <button type="button" id="btn1" class="btn btn-success">変更</button>
  </div>
</body>
</html>

実行結果は、以下となります。

!importantが追加されていることも確認できます。