How to get exact value of css attribute when property is overwritten in css class

Suppose I have li, for example:

<li id="1" class="show" style="display: none;">

and inside the css class I have:

.show {
  display: list-item !important;
}

I wrote:

document.getElementById("1").style.display

to get the value of the display attribute.

and returns "none".

However, due to the .css class, it displayis equal list-item. How can I get the correct and applied value displayusing js?

+4
source share
6 answers

Window.getComputedStyle () can help https://jsfiddle.net/br3t/16uyukxk/

var elem = document.getElementById("li1");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("display");
+3
source

. , .

console.log(document.getElementById("1").style.display)
.show {
  display: list-item !important;
}
<li id="1" class="show" style="display: none;">adsfds</li>
Hide result

, , display: list-item !important;

.

enter image description here

, getComputedStyle,

var elem = document.getElementById("1");

console.log(window.getComputedStyle(elem).display)
.show {
  display: list-item !important;
}
<li id="1" class="show" style="display: none;">adsfds</li>
Hide result

. list-item . .

0

, , window.getComputedStyle:

var display = window.getComputedStyle(element).display

, id , HTML.

0

. http://javascript.info/tutorial/styles-and-classes-getcomputedstyle

getComputedStyle(document.getElementById("1"))["display"]
Hide result
0

Javascript Solution:, getComputedStyle

var elem = document.getElementById("1");
 alert(window.getComputedStyle(elem, null).getPropertyValue("display"));
.show {
  display: list-item !important;
}
<li id="1" class="show" style="display: none;">
Hide result

Jquery Solution: using . css

alert($('#1').css('display'));
.show {
  display: list-item !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="1" class="show" style="display: none;">
Run codeHide result
0
source

You can’t use the inline CSS style, so remove it style="display: none;"from html, create a class .hidden { display: none; }in your css file and apply hidden or show depending on what you want to do. You can then find out if your element is visible or not by checking which CSS class it has.

-1
source

Source: https://habr.com/ru/post/1664552/


All Articles