tags:

views:

90

answers:

2

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

  });

//-->
});
+8  A: 

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.

Nick Craver
dammit nick 8 ^ )
mcgrailm
I like how this removes the need for a conditional branch
mcgrailm
It works in your link, but when I put it in my code, I get a `Uncaught SyntaxError: Unexpected token ILLEGAL`
Jared
@Jared - I sounds like you copied some weird ascii character looking like a space in there...try deleting the spacing around anything you copied.
Nick Craver
I copy/pasted it in notepad to try and get rid of illegal chars, seems to work now, thanks!. But I am not sure I understand WHY this code works? Does replaceWith() have some ability that automatically checks for attributes, and if it doesn't find any, it executes its function?
Jared
@Jared - The `[href='']` is what's checking for the empty `href` attribute...then the `.replaceWith()` is only working on *those* anchors, make sense?
Nick Craver
ahhh I get it now :) Thanks!
Jared
@Jared - welcome :)
Nick Craver
+1  A: 

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
}
meagar
`this.href` is much easier ;)
Nick Craver
doesn't that just check if there is an href attr(), not if it is blank?
Jared
@Nick I sometimes forget that there's this archaic "JavaScript" thing sitting below jQuery :p
meagar
@Jared No, it will return the value of the attribute or `undefined` if it doesn't exist. In JavaScript, `""` (an empty string) is equivalent to boolean false. `attr()` will evaluate to `false` if the attribute doesn't exist or is empty.
meagar
note that IE8 will also return an empty string if the href doesn't exist. The if expression is still valid, but does try href="" and no href as equivalent on IE.
Frank Schwieterman