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

后端 未结 4 735
感动是毒
感动是毒 2021-01-05 04:47

I am getting the child nodes of en element and i want to check if the tags can actually contain text. For example:


,
4条回答
  •  死守一世寂寞
    2021-01-05 05:21

    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);
    

提交回复
热议问题