how to check if div has id or not?

后端 未结 6 534
one
相关标签:
6条回答
  • 2021-01-12 12:49

    Use attribute selector selector[attribute] to get only the elements that have an ID

    $('.myClass[id]')   // Get .myClass elements that have ID attribute
    

    In your case:

    $('.ui-droppable[id]').each(function(){
       alert( this.id );
    });
    

    jsFiddle demo

    0 讨论(0)
  • 2021-01-12 12:55

    demo http://jsfiddle.net/QRv6d/13/

    APi link: http://api.jquery.com/prop/

    Please try this, this should help

    code

       $(".ui-droppable").each(function () { 
    
           if($(this).prop("id").length > 0)
           {
           alert('here');
           }
        });​
    
    0 讨论(0)
  • 2021-01-12 12:58
    if(typeof $(this).attr("id") != 'undefined')
    
    0 讨论(0)
  • 2021-01-12 13:02
    var $this = $(this);
    if (typeof $this.attr("id") != "undefined" && $this.attr("id").length > 0) {
        ...
    }
    

    If you're going to use $(this) more than once, it's advised to find it once, and put the resulting jQuery object in a local variable.

    0 讨论(0)
  • 2021-01-12 13:05

    If there is no id attribute attr method will return undefined. Just write:

    if($(this).attr("id"))
    
    0 讨论(0)
  • 2021-01-12 13:14

    if(this.id) is all you need.


    Why will this work?

    If the element has an ID, the value will a non-empty string, which always evaluates to true.
    If it does not have an ID, the value is an empty string which evaluates to false.


    I am trying to get ids from the loop which are there.

    To get a list of IDs, you can use .map like so:

    var ids = $(".ui-droppable").map(function() {     
        return this.id ? this.id : null;
    }).get();
    

    or use the selector Roko suggests in his answer.

    0 讨论(0)
提交回复
热议问题