Simple question, I have an element which I am grabbing via .getElementById (). How do I check if it has any children?
Simple question, I have an element which I am grabbing via .getElementById () .
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A couple of ways:
or the
hasChildNodes()function:or the
lengthproperty ofchildNodes:If you only want to know about child elements (as opposed to text nodes, attribute nodes, etc.) on all modern browsers (and IE8 — in fact, even IE6) you can do this: (thank you Florian!)
That relies on the
childrenproperty, which wasn’t defined in DOM1, DOM2, or DOM3, but which has near-universal support. (It works in IE6 and up and Chrome, Firefox, and Opera at least as far back as November 2012, when this was originally written.) If supporting older mobile devices, be sure to check for support.If you don’t need IE8 and earlier support, you can also do this:
That relies on
firstElementChild. Likechildren, it wasn’t defined in DOM1-3 either, but unlikechildrenit wasn’t added to IE until IE9. The same applies tochildElementCount:If you want to stick to something defined in DOM1 (maybe you have to support really obscure browsers), you have to do more work:
All of that is part of DOM1, and nearly universally supported.
It would be easy to wrap this up in a function, e.g.: