admin管理员组

文章数量:1429944

I have a form with id mentform and if any logged in user visit the page a p tag gets generated under the form that with class logged-in-as. Now I am trying to check if that p exists and if not exists then do my validation which uses keyup(). Here is a small snippet...

$('form#mentform').keyup(function() {
        if( ! $(this).has('p').hasClass('logged-in-as') ) {
            ....
            } else {
                ......
            }
        }
    });

Now the problem is that the if( ! $(this).has('p').hasClass('logged-in-as') ) is not returning me the expected result whether or not that specific p exists.

Can any of you guys tell me any other/better way to check this?

I have a form with id mentform and if any logged in user visit the page a p tag gets generated under the form that with class logged-in-as. Now I am trying to check if that p exists and if not exists then do my validation which uses keyup(). Here is a small snippet...

$('form#mentform').keyup(function() {
        if( ! $(this).has('p').hasClass('logged-in-as') ) {
            ....
            } else {
                ......
            }
        }
    });

Now the problem is that the if( ! $(this).has('p').hasClass('logged-in-as') ) is not returning me the expected result whether or not that specific p exists.

Can any of you guys tell me any other/better way to check this?

Share Improve this question asked Nov 16, 2015 at 14:50 iSaumyaiSaumya 1,6236 gold badges23 silver badges52 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6
$('form#mentform').keyup(function() {
    if($(this).find('p.logged-in-as').length == 1) {
        ....
        } else {
            ......
        }
    }
});

You can do this to find it.

You can use

if ($('.logged-in-as', this).length)) {

But I would rather use a variable to store that state instead of relying on checking the presence of a raw tag : what if you change your HTML a little ?

Side note: Don't use overqualified selectors. $('#mentform') is faster and logically more consistent than $('form#mentform').

Check if an element witth class "xxx" exist

if( $( ".xxx" ).size() > 0 ) {
  // EXISTS
}

Edit: forgot the dot ( ".xxx" )

本文标签: javascriptHow to check if one element is exist under a form in jQueryStack Overflow