「display: block !important;」指定された要素をjQueryで非表示にする方法
jQueryで特定の要素を非表示にしたかったのでhide()を使用したところ非表示にならなかった。どうもCSS側で当該要素が「display: block !important;」指定されており、これが原因で非表示にならないっぽい。以下に対応方法をメモ。
対応方法
ソースコード
<style>
#test_div{
display: block !important;
width: 300px;
height: 300px;
background-color: #f00;
}
</style>
<div id="test_div">display:block !important;が効いているエリア</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
//非表示にならない
$(`#test_div`).hide();
//非表示になる
$(`#test_div`).attr(`style`, `display: none !important`);
});
</script>
所感
!important指定をさらに!important指定しており、やや無理やり感があるものの、CSS側を変更できないような場合(いただいたコーディングデータとかの場合)はこのような方法を取らざるを得ないかも。
参考サイト
https://stackoverflow.com/questions/18784593/display-none-important-need-to-override-by-using-jquery
関連記事
-
-
要素の点滅
やりたかった事はaタグ内で囲まれている部分を点滅。 <blink>だ ...
-
-
要素の表示or非表示
今まで要素の表示or非表示をCSSで操作する際、 display:none; / ...
-
-
Ajaxで負荷軽減
業務中、専用のページでfile_get_contents的なものは あまり使わな ...
-
-
jQueryで要素を移動する方法のまとめ
jQueryで要素を移動する際、insertBefore / insertAft ...
-
-
jQueryで指定した要素を簡単にフォーカスするfocusbleの使い方
divやspanなど指定した要素を簡単にフォーカスするjQueryプラグインがあ ...