BostonBB
BostonBB

Reputation: 2715

Jquery not selecting proper href's

This script:

$(function() {
    $('a').each(function() {
        var href = $(this).attr('href');
        if ("a:not(http://)") {
            $(this).attr('href', '/' + href);
        }
    });
});

Add the slash to every link even links with the contain "http://" Not sure why? I do not get any errors?

Any ideas on how I can fix this?

Upvotes: 1

Views: 97

Answers (3)

Yogu
Yogu

Reputation: 9445

You mixed up two things:

  • jQuery selectors:

    $(function() {
        $('a:not([href^="http://"])').each(function() {
            var href = $(this).attr('href');
            $(this).attr('href', '/' + href);  
        });
    });
    
  • and pure javascript if statements:

    $('a').each(function() {
       var href = $(this).attr('href');
       if (href.substr(0, 'http://'.length) == 'http://'){
           $(this).attr('href', '/' + href); 
       }   
    });
    

Both do the same.

Note that they will generate invalid links for other schemes than http (e.g. /https://example.com/index.html). Depending on how clean the HTML code you're working with is, you may simply look for the colon to identify absolute links:

$(function() {
    $('a:not([href*=":"])').each(function() {
        var href = $(this).attr('href');
        $(this).attr('href', '/' + href);  
    });
});

Upvotes: 6

Vinyl Windows
Vinyl Windows

Reputation: 503

Just a addon to Yogu,

Remember that your in the context of each tag. "Inside the object itself". So, you can access the href directly.

$('a').each(function() {
   if (this.href.substr(0, 'http://'.length) == 'http://'){
       this.setAttribute('href', '/' + href); 
   }   
});

Upvotes: 0

vittore
vittore

Reputation: 17579

First, you code is equal to the following

$(function() {
   $('a').each(function() {
      var href = $(this).attr('href');
      if(true) { $(this).attr('href', '/' + href); }   
   });
});

if you really want to update href based on condition, if statetment should be different:

$(function() {
   $('a').each(function() {
     var href = $(this).attr('href');
     if(href.indexOf('http://') == -1 ) { $(this).attr('href', '/' + href); }   
   });
});

Another way would be the one offered by @Yogu, where you simple don't loop for links which you are not going to update

Upvotes: 0

Related Questions