简体   繁体   中英

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!

if(contentWrapper.getAttribute("style")){
    if(contentWrapper.getAttribute("style").indexOf("display:") != -1){
        alert("Not Empty");
    } else {
        alert("Empty");
    }
}
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 eg <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)

I missed @plalx's comment the first time I scanned this page.

if (element.hasAttribute("style"))
{
    var styleText = element.getAttribute("style")
}

On a related note, regarding styles...

//to get info about the end results of CSS
var computedStyle = element.currentStyle || getComputedStyle(element, null);

and

//to iterate over css styles from style tags or linked CSS
for i ...
    document.styleSheets[i].rules ...

//great for searching with
var elements = document.querySelectorAll(rules[i].selectorText);

The style object has a length property which tells you if the element has any inline styles or not. This also avoids the problem of having the attribute style being present but empty.

// Would be 0 if no styles are applied and > 0 if there are inline styles applied
contentWrapper.style.length
// So you can check for it like this
contentWrapper.style.length === 0

To check style attribute exist or not for given Id

if(document.getElementById("idname").hasAttribute("style")){
  alert("Style attribute found");
}else{
  alert("Style attribute not found");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM