Is there a clean and robust way in which I can test (using pure javascript or also jQuery) if an HTML element can contain some text?
For instance, <br>
, <hr>
or <tr>
cannot contain text nodes, while <div>
, <td>
or <span>
can.
The simplest way to test this property is to control the tag names. But is this the best solution? I think it is one of the worst...
EDIT: In order to clarify the sense of the question, need to point out that the perfect answer should consider two problems:
Obviously, there is a sub-answer for each point of the previous list.
To check if an element contains specific text: Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the element.
Adding text elements in HTMLSome of the most common HTML elements that make up a webpage are text elements. All the text you read on this website, for example, whether it's the titles at the top of the page, the section headers, or this very text, is made from HTML text elements.
To check if an element contains a class, you use the contains() method of the classList property of the element:*
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 specification "A void element is an element whose content model never allows it to have contents under any circumstances. Void elements can have attributes.").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With