How do I check for empty attr() in jquery?

后端 未结 3 1396
借酒劲吻你
借酒劲吻你 2021-01-02 01:19

I have a few divs that are created using PHP. The anchor within the div always has a HREF, even if it is blank. Basically, I am trying to detect if the HREF is blank. If it

相关标签:
3条回答
  • 2021-01-02 01:58

    You can simply test the attribute as a boolean instead of testing it against undefined:

    if ($(this).attr('href')) {
      // href is not blank
    } else {
      // href is blank
    }
    
    0 讨论(0)
  • 2021-01-02 02:04

    To simply get rid of the 'href' attribute:

    $("#myLink[href='']").removeAttr('href');
    

    For multiple targeting, for example the 'style' attribute:

    $("#myDiv td, a, p, table, nav, header[style='']").removeAttr('style');
    

    This way, you'll only get rid of the Attribute when it's empty instead of deleting the whole element itself.

    A full code example would be:

    $('#myDiv table, tr, td, a, p').each(function() { 
    if ($(this).attr('style') == '') { 
        $(this).removeAttr('style'); 
    } 
    })
    
    0 讨论(0)
  • 2021-01-02 02:05

    You can check for an empty href attribute and "unwrap" those links using .replaceWith() like this:

    $(".article[href='']").replaceWith(function() { return this.innerHTML; });
    

    You can give it a try here.

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