Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect inline/block type of a DOM element

Tags:

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.

like image 639
abernier Avatar asked May 21 '10 09:05

abernier


People also ask

How do I identify a DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.

Is UL element block or inline?

Block-level elements that you've seen so far include: Headings. Paragraphs (p) Lists and list items (ul, ol, li)

Is label tag inline or block?

According to the MDN pages, label elements "are simple inline elements".


2 Answers

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),         gcs = "getComputedStyle" in window;      document.body.appendChild(t);     cStyle = (gcs ? window.getComputedStyle(t, "") : t.currentStyle).display;      document.body.removeChild(t);      return cStyle; } 

Tested in latest Firefox, Chrome and IE7/IE8.

Results:

> getElementDefaultDisplay("a") inline > getElementDefaultDisplay("div") block 

Update: edited to give preference to standards compliance/getComputedStyle() in IE9, which supports both methods.

like image 175
Andy E Avatar answered Oct 11 '22 08:10

Andy E


The traditional and rather ugly way of doing this is to consult a list of element names for block-level elements:

var blockRegex = /^(address|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i;  function isBlockLevel(el) {     return blockRegex.test(el.nodeName); } 
like image 22
Tim Down Avatar answered Oct 11 '22 10:10

Tim Down