I want to find out if an element is empty or not. Probably this is one of the best examples to help people understand difference between innerText and innerHTML as well.
Here are the examples:
1. <div> <!-- Just a comment node is present inside a div --> </div>
2. <div> <span></span> </div>
3. <div> hi </div>
4. <div> hello <!-- world --> I know javascript </div>
5. <div> </div>
Example_Number | innerHTML | innerText | #childElements | isElementEmpty(Result)
1............................| Not Empty....| Empty........| 0.........................| YES
2............................| Not Empty....| Empty........| 1.........................| No
3............................| Not Empty....| Not Empty..| 0.........................| No
4............................| Not Empty....| Not Empty..| 0.........................| No
5............................| Empty..........| Empty.........| 0.........................| Yes
In #5, trimmed value is considered.
Clearly, innerHTML does not contribute to check whether an element is empty or not. Now, we need to check how innerText/textContent and numberOfChildElement contribute. So based on above findings, I have concluded
An element is empty when both of these conditions is met.
- Trimmerd innerText/textContent is empty. (Satisfies #5)
- Number of child elements is ZERO. (Satisfies #2)
So the code becomes
function isEmpty(element) {
return (element.textContent.trim() && element.childElementCount == 0);
}
I just want to validate my approach and tell if I miss any use case here or a better solution would be really helpful.