Check if an element is closed using a discrete tag with JavaScript

dom, html, javascript, nodes

Solution

Unfortunately, there is no way to detect how a tag was written in the code, since when the JavaScript runs, the HTML code has already been parsed into DOM objects.

However, your question seems to be more about whether a particular element type can contain text. This simple test will give you an answer per element type:

function canElementContainText(tagname) {
    try {
        var e = document.createElement(tagname);
        return e.outerHTML.indexOf("/") != -1;
    } catch (ex) {
        return false;
    }
}

For instance `canElementContainText("div")` returns `true` and `canElementContainText("img")` returns `false`.

You can then pass the `tagName` property of any element to this function to test it.

var result = canElementContainText(myElement.tagName);

Problem

I am getting the child nodes of en element and i want to check if the tags can actually contain text. For example: ``` <br />, <img /> ``` Should return false and ``` <span></span>, <div></div>, <li></li> ``` should return true. Thanks!

Original source