How to check empty attr () in jquery?

I have several divs that are created using PHP. An anchor inside a div always has HREF, even if it is empty. Basically, I am trying to determine if the HREF is empty. If it has content, do nothing, if it is empty, delete the text, remove the binding, they will return the text.

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); } }); //--> }); 
+7
jquery attr each
source share
3 answers

You can check the empty href attribute and "expand" these links with .replaceWith() as follows:

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

You can try it here .

+15
source share

You can simply check the attribute as a boolean and not test it with undefined :

 if ($(this).attr('href')) { // href is not blank } else { // href is blank } 
+12
source share

To just get rid of the 'href' attribute:

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

For multiple targeting, such as the 'style' attribute:

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

Thus, you will get rid of the attribute when it is empty, instead of deleting the entire element.

Full code example:

 $('#myDiv table, tr, td, a, p').each(function() { if ($(this).attr('style') == '') { $(this).removeAttr('style'); } }) 
+1
source share

All Articles