Hi,
How to detect whether a DOM element is block or inline with javascript?
For example, is there a function/property which returns 'inline' for a '<a>
' tag (or 'block' for a '<p>
' tag)?
Thank you.
Hi,
How to detect whether a DOM element is block or inline with javascript?
For example, is there a function/property which returns 'inline' for a '<a>
' tag (or 'block' for a '<p>
' tag)?
Thank you.
the information you need should be in the display property within style.
element.style.display
Of course this will vary between browsers I expect like everyhting in javascript.
You can go with getComputedStyle()
and currentStyle
to get the calculated styles for an element. This should do it:
function getDisplayType (element)
{
var cStyle = element.currentStyle || window.getComputedStyle(element, "");
return cStyle.display;
}
To be a little clearer, computed styles contain values for every style property, even for those that don't have a style property set. Those values will be the default value so in the case of an unstyled <a>
element, display
will return inline
:
function getElementDefaultDisplay(tag)
{
var cStyle,
t = document.createElement(tag);
document.body.appendChild(t);
cStyle = (t.currentStyle || window.getComputedStyle(t, "")).display;
document.body.removeChild(t);
return cStyle;
}
Tested in latest Firefox, Chrome and IE7/IE8.
Results:
> getElementDefaultDisplay("a") inline > getElementDefaultDisplay("div") block
The traditional and rather ugly way of doing this is to consult a list of element names for block-level elements:
var blockLevelElements = [
"address", "blockquote", "body", "center", "dir", "div",
"dl", "fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6",
"hr", "isindex", "menu", "noframes", "noscript", "ol", "p",
"pre", "table", "ul", "dd", "dt", "frameset", "li", "tbody",
"td", "tfoot", "th", "thead", "tr", "html"
];
function contains(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
}
function isBlockLevel(el) {
return contains(blockLevelElements, el.nodeName.toLowerCase());
}