Reputation: 980
Is there a portable way to check if some element can accept and show childNodes, except checking tagName switch(node.tagName)
or alike? I need to implement some kind of d&d and I'd like to insert moved node in the nearest to document.elementFromPoint
position (where dragged node has been dropped). But, as I understand, it's meaningless to insert an element in the <img>
, for example, so I'll need to insertBefore
this img's parentNode in that case.
Of course, it is possible to check against tags list, but maybe there's more portable and simple solution?
Thank you
Upvotes: 4
Views: 195
Reputation: 5517
You may use method from this answer (The question and answer are not mine). It answers different question but may still be helpful. I'm pasting here the accepted answer, although there are also other answers in this question, may be useful to you. This is a check whether the element can contain text
function canElementContainText(tagname) {
try {
var e = document.createElement(tagname);
return e.outerHTML.indexOf("/") != -1;
} catch (ex) {
return false;
}
}
Usage:
var result = canElementContainText(myElement.tagName);
Upvotes: 1
Reputation: 664886
No, I don't think there's a builtin function to check whether a certain tag is a void one. It's a pretty arbitrary decision of HTML, there's no DOM attribute for it. (In XML documents, every element can theoretically have children).
So checking against the official list is indeed the way to go. For HTML4, see Which HTML tags have no content, for HTML5 see the list of void elements in the spec:
area, base, br, col, embed, hr, img, input, keygen, link, menuitem, meta, param, source, track, wbr
Upvotes: 5