jQuery using 'this' in an if statement

前端 未结 3 1752
南方客
南方客 2021-02-07 21:56

I\'m using an if statement in order to determine if an element has any children. If it does NOT have any children, I want to do something to that element only.

相关标签:
3条回答
  • 2021-02-07 22:12

    you could use each to iterate through elements

    $('input').each(function(){
      if ($(this).val()) {
        $(this).addClass('has-value');
      }
    });
    
    0 讨论(0)
  • 2021-02-07 22:17

    Edit: Added DEMO Link

    You can use .filter to check the condition and call .hide on the filter results. See below,

    $("#div a").filter(function () {
      return ($(this).children().length > 0)
    }).hide();
    
    0 讨论(0)
  • 2021-02-07 22:26

    Simple solution is to place the element in a variable.

    var elem = $("#div a");
    if (elem.children().length > 0){
        elem.hide();
    }
    
    0 讨论(0)
提交回复
热议问题