Home > other >  jquery check a div to see if it has any text in it
jquery check a div to see if it has any text in it

Time:05-16

I would like to use jQuery to check if a div has any text in it. if it does then show the div otherwise hide it.

for example:

<div id="demo_div"></div>

<script>
$( document ).ready(function() {
    if ($("#demo_div") has some text) {

    $("#demo_div").show();
    }
    else
   {
   $("#demo_div").hide();
   }
    });

which jQuery function should I use to detect if the div has text inside?

Thank you!

CodePudding user response:

  1. First identify the textual content of the div
  2. Trim it to remove any trailing white space

let showHide = function($selector)
{
  let text = $selector.text().trim();

  if (text.length > 0)
  {
    console.log("showing", $selector.attr("id"));
    $selector.show();
  }
  else
  {
    console.log("hiding", $selector.attr("id"));

    $selector.hide();
  }
}


showHide($("#demo_div") );
showHide($("#demo_div2") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo_div"> 1</div>

<div id="demo_div2"></div>

CodePudding user response:

You can use either text() or html() functions in jquery then check if the returned string is longer than zero. You can optionally trim() the result too if you dont want whitespace being considered.

<div id="demo_div"></div>

<script>
$( document ).ready(function() {
   if ($("#demo_div").text().trim().length > 0) {
      $("#demo_div").show();
   }
   else
   {
      $("#demo_div").hide();
   }
});
</script>

As the name suggest text() retrieves textual part of the node while html() retrieves everything including html tags. You can choose whichever suits your need.

CodePudding user response:

if ($("#demo_div").is(':empty')) {
   // Whatever you want to do
}

This might solve your problem but remember that line breaks or white spaces are not considered as empty.

For more general case, like you want to remove white spaces and check. In that case you can use trim function along with html method like this

if (!$.trim($("#demo_div").html()) {
  // Process
}
  • Related