How to check if one element in a form exists in jQuery

I have a form with id commentform, and if any registered user visits the page, the tag is pgenerated in the form, which is with the class logged-in-as. Now I'm trying to check if this exists p, and if not, then do my check, which uses keyup(). Here is a small snippet ...

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

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

Can any of you tell me any other / best way to test this?

+4
source share
3 answers

you can use

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

, : , HTML?

. . $('#commentform') , $('form#commentform').

+4
$('form#commentform').keyup(function() {
    if($(this).find('p.logged-in-as').length == 1) {
        ....
        } else {
            ......
        }
    }
});

, .

+6

Check if class exists with class "xxx"

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

Edit: forgot point (".xxx")

+1
source

Source: https://habr.com/ru/post/1616074/


All Articles