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

风流意气都作罢 提交于 2019-11-29 17:50:49

问题


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 has content, do nothing, if it's blank, strip the text out, delete the anchor, them put the text back in.

Here is the div:

<div class="title"> 
    <a class="article" href="">Lorem Ipsum</a> 
</div> 

Here is my code:

jQuery(document).ready(function($) { //required for $ to work in Wordpress

    $(".article").each(function(){
        if ($(this).attr('href') !== undefined) {
            return;
        } else {
            var linkTitle = $(this).html();
            $(this).parent().empty().html(linkTitle);
        }                               
    });    
//-->
});

回答1:


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.




回答2:


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
}



回答3:


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'); 
} 
})


来源:https://stackoverflow.com/questions/3773195/how-do-i-check-for-empty-attr-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!