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!
An opening tag begins a section of page content, and a closing tag ends it. For example, to markup a section of text as a paragraph, you would open the paragraph with an opening paragraph tag <p> and close it with a closing paragraph tag </p> (closing tags always proceed the element with a /).
A self-closing tag is an element of HTML code that has evolved in the language. Typically, the self-closing tag makes use of a “/” character in order to effectively close out a beginning tag enclosed in sideways carets.
In the left pane of the code view you can see there <> highlight invalid code button, click this button and you will notice the unclosed div highlighted and then close your unclosed div. Press F5 to refresh the page to see that any other unclosed div are there. You can also validate your page in Dreamweaver too.
Div tag has both open(<div>) and closing (</div>) tag and it is mandatory to close the tag. The Div is the most usable tag in web development because it helps us to separate out data in the web page and we can create a particular section for particular data or function in the web pages.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With