Test the div2.
In the first case, there is tex...">

Javascript test if div has text in it

1. <div id="div_Msg"> Test the div </div>
2. <div id="div_Msg"> </div>

In the first case, there is text in the div. In the second case, the text is missing. Using javascript, how can it be tested if the div has text in it.

+3
source share
2 answers

If you are using jQuery, you can do it like this:

if($.trim($('#div_Msg').text()) != "") {
    // Code here
}

In simple JavaScript, do the following:

if(document.getElementById("div_Msg").innerHTML.replace(/^\s*/, "").replace(/\s*$/, "") != "") {
    // Code here
}

Both cases get the text and trim the spaces from the beginning and end of the line, and then compare them with the empty line.

+7
source

If you use jQuery you can do:

$.trim($('#div_Msg').text());

Note: items may not have the sameid

0
source

Source: https://habr.com/ru/post/1781312/


All Articles