jQuery if Element has an ID?

前端 未结 11 2015
北恋
北恋 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:34

    Simply use:

    $(".parent a[id]");
    
    0 讨论(0)
  • 2020-12-25 10:35

    Pure js approach:

    var elem = document.getElementsByClassName('parent');
    alert(elem[0].hasAttribute('id'));
    

    JsFiddle Demo

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

    You can do

    document.getElementById(id) or 
    $(id).length > 0
    
    0 讨论(0)
  • 2020-12-25 10:42

    You can using the following code:

       if($(".parent a").attr('id')){
    
          //do something
       }
    
    
       $(".parent a").each(function(i,e){
           if($(e).attr('id')){
              //do something and check
              //if you want to break the each
              //return false;
           }
       });
    

    The same question is you can find here: how to check if div has id or not?

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

    You can use jQuery's .is() function.

    if ( $(".parent a").is("#idSelector") ) {

    //Do stuff
    

    }

    It will return true if the parent anchor has #idSelector id.

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

    You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.

    See fiddle here.

    $('a').each(function() {
        $(this).click(function() {
            var el= $(this).attr('id');
            if (el === 'notme') {
                // do nothing or something else
            } else {
                $('p').toggle();
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题