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

耗尽温柔 提交于 2019-11-30 03:31:06

问题


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!


回答1:


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



回答2:


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



回答3:


use that:

canContainText: function(node) {
    if(node.nodeType === 3){
        return true;
    }
    if(node.nodeType === 1){
        return /<[^>]+><\/[^>]+>/gi.test(document.createElement(node.nodeName.toLowerCase())).outerHTML;
    }
}



回答4:


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


来源:https://stackoverflow.com/questions/22046163/check-if-an-element-is-closed-using-a-discrete-tag-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!