Reputation: 153
how to check div tag its empty or not by using java script?
HTML
<div class="txt"></div>
JS
<script>
if(txt != null ){
document.write("There is content in that div");
}else{
document.write("There is NO content in that div");
}
</script>
I already tried, but shows always "there is a content in this divtag".
Upvotes: 0
Views: 2292
Reputation: 15860
You need to use the html()
to check the contents as
var txt = $('div').html();
/* if you just want to use Plain JS then */
var txt = document.getElementsByTagName("div")[0].innerHTML;
if (txt != null ) {
document.write("There is content in that div");
} else {
document.write("There is NO content in that div");
}
Otherwise you can replace the html()
method with text()
method too. Text won't search for the HTML content, but will search for the text content, such as the content that is shown to the user in the Browser.
Upvotes: 0
Reputation: 10132
Native Javascript way:
Check text contents:
var sTextContents = document.getElementsByClassName('txt')[0].textContent;
if (sTextContents != "") {
//text contents exists
}
Check HTML contents:
var sHTMLContents = document.getElementsByClassName('txt')[0].innerHTML;
if (sHTMLContents != "") {
//html contents exists
}
Upvotes: 2
Reputation: 701
You can use the innerHTML property of the element, i.e. if the div has id divid:
if (document.getElementById('divid').innerHTML != "") {
...
}
This is non-jQuery javascript, but should work as well, albeit possibly less aesthetic if used along jQuery code.
Upvotes: 1
Reputation: 16723
This will check if there is any textual content:
$('div').text() === ''
This will check if there is anything at all, including markup:
$('div').html() === ''
Of course, you probably want to specify a specific div
, this one will act upon every div
in your document which is certainly not what you want.
Upvotes: 0