Reputation: 1345
Assume I have li
such as:
<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 display attribute.
and it returns "none"
.
However, because of the .css class, it's display
is list-item
.
How can I get the correct and applied value of display
with js?
Upvotes: 4
Views: 388
Reputation: 7107
It's just returning style attribute's display property value. Thats you have in your markup.
console.log(document.getElementById("1").style.display)
.show {
display: list-item !important;
}
<li id="1" class="show" style="display: none;">adsfds</li>
But in the browser's output you can see in the inspect element, the display: list-item !important;
was applied
see the below image
To get the actual applied style, you can use the getComputedStyle
as below
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>
Note : You don't need to set the list-item
to a list item. Its always a list-item by default.
Upvotes: 0
Reputation: 13828
You are looking for the style that is actually used to render the element, you need window.getComputedStyle
:
var display = window.getComputedStyle(element).display
By the way, id
must not be started with number, it's invalid HTML.
Upvotes: 0
Reputation: 18987
Javascript Solution: using 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;">
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;">
Upvotes: 0
Reputation: 263
You are looking for the computed style. See this http://javascript.info/tutorial/styles-and-classes-getcomputedstyle
getComputedStyle(document.getElementById("1"))["display"]
Upvotes: 0
Reputation: 1658
Window.getComputedStyle() can help https://jsfiddle.net/br3t/16uyukxk/
var elem = document.getElementById("li1");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("display");
Upvotes: 3
Reputation: 627
You should not use inline css style, so remove style="display: none;"
from the html, create a .hidden { display: none; }
class in your css file and apply hidden or show depending of what you want to do. You will then be able to know if your element is visible or not by checking which CSS class it has.
Upvotes: -1