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?
It's pretty simple:
if (element.innerHTML) {
// element has content
} else {
// element is empty
}
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 = "";
};
jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With