tracer tong
tracer tong

Reputation: 553

jquery .text as a conditional

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

Answers (6)

Antonio
Antonio

Reputation: 11

another option:

if ($('#feedback p:empty').length) {
    alert("empty");
} else {
    alert("has content");
}

Upvotes: 0

Andrei R
Andrei R

Reputation: 111

You can use:

if($('#feedback').is(':empty')) {
   alert("no content");
} else {
   alert("has content");
}

Upvotes: -1

JJJ
JJJ

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

Royi Namir
Royi Namir

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

j08691
j08691

Reputation: 207901

Shouldn't it be:

if ($('#feedback').text() != "") {
    alert("has content");
} else {
    alert("no content");
}

Upvotes: 0

Andreas Nilsson
Andreas Nilsson

Reputation: 231

It is reverted...

alert($('#feedback').text());
if ($('#feedback').text() == "") {
    alert("no content");
} else {
    alert("has content");
}

Its fixed now :)

Upvotes: -1

Related Questions