Skip to content
Advertisement

Default beginning value of innerHTML of a div

In my app, I need to check if a div container is empty before appending certain text elements to it (the innerHTML is created and removed many times in my app, hence the need to check for emptiness). The div is created very simply as below in the beginning. Why doesn’t checking for an empty string as below work? I am expecting the alert to show the text Nothing, but it does not.

let targetContainer = document.getElementById("container")
let containerText = targetContainer.innerHTML
alert("Text: " + containerText == "" ? "Nothing" : containerText)
#container {
  background-color: #0f2e0c;
}
<div id="container"></div>

Advertisement

Answer

Your main issue is with operator precedence. Currently, you code is evaluating like so:

("Text: " + containerText) == "" ? "Nothing" : containerText

in your code + has higher operator precedence than ==, meaning that the concatenation occurs before the == occurs. You can force the evaluation of the equality and the ternary to occur before the addition concatenation occurs by wrapping it in parenthesis to group your ternary operation. Since grouping has the highest operator precedence it will occur before your concatenation occurs:

"Text: " + (containerText == "" ? "Nothing" : containerText)

let targetContainer = document.getElementById("container")
let containerText = targetContainer.innerHTML
alert("Text: " + (containerText == "" ? "Nothing" : containerText));
#container {
  background-color: #0f2e0c;
}
<div id="container"></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement