Reputation: 553
I have this code: (jquery)
alert($('#feedback').text());
if ($('#feedback').text() == "") {
alert("has content");
} else {
alert("no content");
}
Which I am using to test the #feedback div for any plan text content. Yet no matter how I format the condition, the else statement always fires regardless of whether I have content or not.
Where am I going wrong here?
html:
<div id="feedback" class="hide feedback">
<p>generated message</p>
</div>
Upvotes: 3
Views: 3071
Reputation: 11
another option:
if ($('#feedback p:empty').length) {
alert("empty");
} else {
alert("has content");
}
Upvotes: 0
Reputation: 111
You can use:
if($('#feedback').is(':empty')) {
alert("no content");
} else {
alert("has content");
}
Upvotes: -1
Reputation: 33163
Based on the HTML example I assume you have something like this when the div is supposed to be empty:
<div id="feedback" class="hide feedback">
<p></p>
</div>
In that case the .text()
of the div is not ""
, it's "\n\n"
(two line breaks). You need to remove the line breaks with $.trim()
. (The same is true even if there are no <p>
tags if the line breaks are there.)
if( $.trim( $( '#feedback' ).text() ) == "" ) {
alert( "no content" );
} else {
alert( "has content" );
}
Upvotes: 3
Reputation: 148524
Just for checking !
Check your : $('#feedback').length
value
if ($('#feedback').length>0 && $.trim($('#feedback').text()) != "") {
alert("has content");
} else {
alert("no content"); // or no element
}
Upvotes: 1
Reputation: 207901
Shouldn't it be:
if ($('#feedback').text() != "") {
alert("has content");
} else {
alert("no content");
}
Upvotes: 0
Reputation: 231
It is reverted...
alert($('#feedback').text());
if ($('#feedback').text() == "") {
alert("no content");
} else {
alert("has content");
}
Its fixed now :)
Upvotes: -1