I am creating an If…Else statement and need to check if the element has innerHTML / textContent. Like this:
if (<span class="event"> *yet has some text inside*) {do smth} else {do smth else};
So, how do I do that using Javascript? Please, help!
UPD! I have dynamically changing content, and
element.innerHTML
seems not working after I put some text inside my < span >. I mean it still thinks the < span > is empty. Any cure for that?
Advertisement
Answer
Check the innerHTML
of the span using document.getElementsByClassName("ClassName");
. You need to index
it as you may have more than one element with same class name. Add text inside span
dynamically on button click. And check again if it effects the output. Try this way,
HTML :
<span class="event"></span> <button id="addTextButton">Add Text In Span</button> <button id="removeSpanTextButton">Empty Span</button> <button id="checkSpanButton">Check Span Content</button>
javaScript :
var spanContent = document.getElementsByClassName("event")[0]; checkSpanButton.onclick = function(){ if(spanContent.innerHTML == ""){ alert("Span is empty.."); } else{ alert("Span Text : " + spanContent.innerHTML); } }; // dynamically add text addTextButton.onclick = function(){ spanContent.innerHTML = "Added This Text."; }; removeSpanTextButton.onclick = function(){ spanContent.innerHTML = ""; };