I have a div
<div id="myDiv" style="border:1px solid white; width:20px; height: 100px">....</div>
now in Js, if border
css property is already present I need to remove that by using
let element = document.getElementById("myDiv")
element.style.removeProperty("border");
if border
css property not present, need to add
let element = document.getElementById("myDiv")
element.style.border = '1px solid white'
but, How to check whether the css property(border
) exists or not in element(myDiv
)
2
Answers
This might be an xy problem, however its often useful to be able to check details on the current computed css. You’re probably looking for the Window method
getComputedStyle()
.Something to keep in mind, this will not let you know if you set the style, just what is currently rendered by the browser. A good idea is to check if it is your desired style, if not, apply your desired style.
Enjoy this small demo of
getComputedStyle
.Of course it’s often better just to toggle a class that encapsulates your css, hopefully this answers the question you had. If you need any clarification, don’t hesitate to ask.
As others have already pointed out, you can just use a simple
if
condition to check for the existence of a particular style. If you look for the existence of acolor
in an inline style, it’d be:The below example uses exactly this in
toggleStyle
: