I am getting the child nodes of en element and i want to check if the tags can actually contain text. For example:
,
use that:
canContainText: function(node) {
if(node.nodeType === 3){
return true;
}
if(node.nodeType === 1){
return /<[^>]+><\/[^>]+>/gi.test(document.createElement(node.nodeName.toLowerCase())).outerHTML;
}
}
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
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);
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