Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 700
Ood Avatar asked Feb 26 '14 15:02

Ood


People also ask

How do you identify a closing tag?

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 /).

What is a closing tag in Javascript?

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.

How do I know if a div is not closed?

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.

Is DIV tag self closing?

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.


2 Answers

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);
like image 108
wizulus Avatar answered Oct 19 '22 13:10

wizulus


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
like image 37
nanobash Avatar answered Oct 19 '22 13:10

nanobash