Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

each

attr

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);
        }                               
    });    
//-->
});
like image 648
Jared Avatar asked Sep 22 '10 20:09

Jared


1 Answers

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
}
like image 137
meagar Avatar answered Oct 15 '22 05:10

meagar