Check if element is closed using discrete tag with JavaScript

I get the children of the en element and I want to check if the tags can really contain text. For example:

<br />, <img /> 

Should return false and

 <span></span>, <div></div>, <li></li> 

should return true. Thanks!

+7
javascript dom html nodes
source share
3 answers

Unfortunately, there is no way to determine how the tag was written in the code, because when you run JavaScript, the HTML code is already parsed for DOM objects.

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

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

For example, canElementContainText("div") returns true and canElementContainText("img") returns false .

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

 var result = canElementContainText(myElement.tagName); 
+8
source share

After the script it works just fine (cross-browser problem 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
source share

You can 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 
-4
source share

All Articles