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

In the first instance there is the text in the div. In the second instance there is no text. Using javascript how can it be tested if a div has text in it.

0

2 Answers 2

7

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

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

In just plain JavaScript, do this:

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

Both cases get the text and trim whitespace off the beginning and end of the string, then compare it to an empty string.

Sign up to request clarification or add additional context in comments.

2 Comments

Is trim really necessary? This works for me: if($('#div_Msg').text()) {}
In the example, the div without text has a space in it. The trim removes the space. If you are sure there wil be no whitespace, then you don't need the trim.
0

If using jQuery, you can do:

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

Note: elements cannot have the same id

3 Comments

That doesn't work. There is a space in the div and therefore a nextnode. At least in some browsers.
As @Mark says, you would need to $.trim() that value before checking against an empty string: if ($.trim($('#div_Msg').text()) != '') { ..
if($('[id$=div_Msg]').text() == null) { alert("yes text is not there"); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.