4

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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
BUKTOP
  • 867
  • 10
  • 22
  • 2
    what's wrong with checking against a list of tags? – Manos Kounelakis Dec 25 '17 at 07:48
  • Who said that it's wrong? This list just will be a bit large and can be changed in the future, so maybe there is a simpler way to do that? Just look here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element - it's not so small, isn't it? )) – BUKTOP Dec 25 '17 at 07:52
  • 2
    You need to know more than "can have children" anyway, since there are many elements that can only be children of specific other elements, e.g. TD must be a child of TR and LI must be a child of UL or OL. Similarly, some elements can only have specific child nodes, e.g. TR can only have TD children, and so on. – RobG Dec 25 '17 at 08:57

2 Answers2

5

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
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Well, it's not exactly what I'm lloking for, but close. In my case it's also meaningless to insert into lists or selects etc. Ok, maybe it's really depends on purpose and approach. Thank you, gone writing switch-case list then )))) – BUKTOP Dec 25 '17 at 08:18
  • @BbIKTOP You can inserts `
  • `s in lists and `
  • – Bergi Dec 25 '17 at 08:28
  • Of course, but it’s useless to insert anything else than li in the list, that ’s what I meant. I have to make my own list for this particular case then – BUKTOP Dec 25 '17 at 08:32
  • Again, don't make your own but use the [official list](https://www.w3.org/TR/html51/fullindex.html#index-elements) :-) – Bergi Dec 25 '17 at 09:33
  • As I said, there’s no list for my task ) but at least now I understand it )) – BUKTOP Dec 25 '17 at 09:49
  • As I said in the question, i'm implementing some kind of d&d and need to insert "dropped" element at the drop place. Well, I've got enough info to realize what I really need, thank you! – BUKTOP Dec 25 '17 at 10:01