Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there's some text inside an element

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?

like image 746
Alexandr Belov Avatar asked Mar 18 '23 04:03

Alexandr Belov


2 Answers

It's pretty simple:

if (element.innerHTML) {
    // element has content
} else {
    // element is empty
}
like image 71
Acidic Avatar answered Mar 29 '23 16:03

Acidic


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

like image 37
Md Ashaduzzaman Avatar answered Mar 29 '23 17:03

Md Ashaduzzaman