jQuery if Element has an ID?

前端 未结 11 2016
北恋
北恋 2020-12-25 10:01

How would I select elements that have any ID? For example:

if ($(\".parent a\").hasId()) {
    /* then do something here */
}

I, by no mean

相关标签:
11条回答
  • 2020-12-25 10:45

    Number of .parent a elements that have an id attribute:

    $('.parent a[id]').length
    
    0 讨论(0)
  • 2020-12-25 10:45

    You can do this:

    if ($(".parent a[Id]").length > 0) {
    
        /* then do something here */
    
    }
    
    0 讨论(0)
  • 2020-12-25 10:50

    Like this:

    var $aWithId = $('.parent a[id]');
    

    Following OP's comment, test it like this:

    if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
    

    Will return all anchor tags inside elements with class parent which have an attribute ID specified

    0 讨论(0)
  • 2020-12-25 10:53

    Simple way:

    Fox example this is your html,

    <div class='classname' id='your_id_name'>
    </div>
    

    Jquery code:

    if($('.classname').prop('id')=='your_id_name')
    {
        //works your_id_name exist (true part)
    }
    else
    { 
        //works your_id_name not exist (false part)
    }
    
    0 讨论(0)
  • 2020-12-25 10:56

    I seemed to have been able to solve it with:

    if( $('your-selector-here').attr('id') === undefined){
        console.log( 'has no ID' )
    }
    
    0 讨论(0)
提交回复
热议问题