Test if an element can contain text

The W3 standard for “void elements” specifies:

Void elements
area, base, br, col, embed, hr, img, input, keygen, link, menuitem, meta, param, source, track, wbr

And apparently there’s some unofficial tags as well.

You can make a black list and use .prop('tagName') to get the tag name:

(function ($) {
    var cannotContainText = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];

    $.fn.canContainText = function() {
        var tagName = $(this).prop('tagName').toUpperCase();

        return ($.inArray(tagName, cannotContainText) == -1);
    };
}(jQuery));

$('<br>').canContainText(); //false
$('<div>').canContainText(); //true

Here you can also add your own tags to cannotContainText (eg. to add <tr> which is not officially a void element as it doesn’t match the specificationA void element is an element whose content model never allows it to have contents under any circumstances. Void elements can have attributes.“).

Leave a Comment