Search code examples
javascripthtmlcssstyles

How to check if HTML style attribute exists with javascript


I'm trying to find out if a specific element has an inline style attribute or not: I'm sure there's an easy method to check this, but I can't seem to find it. I tried multiple things already including this:

var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");

Thank you for your help!


Solution

  • if(!contentWrapper.getAttribute("style"))
    

    OR

    if(contentWrapper.getAttribute("style")==null || 
       contentWrapper.getAttribute("style")=="")    
    

    the above lines will work for you (anyone can be chosen).

    In second solution:

    first check watches if style attribute is present in the element, 2nd check ensures that style attribute is not present as an empty string e.g. <div id="contentWrapper" style="">

    Complete code is given below:

    var contentWrapper = document.getElementById("contentWrapper");
    if(contentWrapper.getAttribute("style")==null || contentWrapper.getAttribute("style")=="")
    alert("Empty");
    else
    alert("Not Empty");
    

    http://jsfiddle.net/mastermindw/fjuZW/ (1st Solution)

    http://jsfiddle.net/mastermindw/fjuZW/1/ (2nd Solution)