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

后端 未结 4 709
感动是毒
感动是毒 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:10

    use that:

    canContainText: function(node) {
        if(node.nodeType === 3){
            return true;
        }
        if(node.nodeType === 1){
            return /<[^>]+><\/[^>]+>/gi.test(document.createElement(node.nodeName.toLowerCase())).outerHTML;
        }
    }
    
    0 讨论(0)
  • 2021-01-05 05:20

    Following script works just fine (cross-browser issue resolved):

    function containTxt(tag) {
        var tags = /^(img|video)$/i; // any values which will be in `tags` set will be treated as they can't have a text value
        return !tags.test(tag);
    }
    
    console.log(containTxt("img")); // returns false
    console.log(containTxt("div")); // returns true
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-05 05:25

    Could use RegEx:

    // these are samples, get elements text using element.innerHTML;
    var one = "<a href='something'>Links</a>";
    var two = "Lorem ipsum dolor";
    
    function check(str){
        return str.match(/<[a-zA-Z]+.*>(.|\n)*<\/[a-zA-Z]+>/) ? true : false;
    }
    
    console.log(check(one)); // true
    console.log(check(two)); // false
    
    0 讨论(0)
提交回复
热议问题