最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - javascript test if div has text in it - Stack Overflow

programmeradmin7浏览0评论
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.

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.

Share Improve this question edited Dec 20, 2010 at 20:42 Pinu asked Dec 20, 2010 at 20:40 PinuPinu 7,52016 gold badges55 silver badges77 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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 pare it to an empty string.

If using jQuery, you can do:

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

Note: elements cannot have the same id

发布评论

评论列表(0)

  1. 暂无评论