What’s causing “Cannot read property ‘substr’ of undefined” error on WordPress using jQuery?

I’m listing some user generated links on a page. The problem is that not all users are adding “http://” to their urls, which is messing things up.

In response to this I’ve used this piece of jQuery (“$” replaced with “jQuery” due to noconflict mode) to try to detect whether http:// is present and add it if it’s not:

Read More
jQuery('.theirsite').each(function(){
    var currentlink = jQuery(this);
    var linkloc = currentlink.attr('href');
    var httpcheck = linkloc.substr(0,7);
    if(httpcheck!="http://"){
            currentlink.attr('href','http://'+linkloc);
    }
});

But it’s not working, and I’m seeing this error in Chrome’s console:

Uncaught TypeError: Cannot read property 'substr' of undefined (index):456
(anonymous function) (index):456
x.extend.each jquery.js:3
x.fn.x.each jquery.js:3
(anonymous function)

This is the php I’m using:
<div class="theirsite"><?php echo '<a href="' . $user_info->user_url . '" class="button"> Visit their website </a>';?></div>

The whole thing is on WordPress. Apologies if I’ve left anything out or not seen anything obvious. All pointers appreciated.

Related posts

Leave a Reply

2 comments

  1. Your .theirsite element does not have an href attribute, it is a div.

    You should change:

    jQuery('.theirsite').each(function(){
    

    to something like:

    jQuery('.theirsite a').each(function(){
    
  2. maybe this will do:

    first of all, i declare jQuery to $, so you dont have to type jQuery all the time.
    then comes the ready handler.
    then the each part, where you look up the a element and check, if the url contains http://
    i also wrote the check for https. should work..

    (function($) {
      $(function() {
        $('.theirsite').each( function() {
          url = $(this).find("a").attr("href");
          if (url.indexOf("http://") !== -1 && url.indexOf("https://") !== -1) {
            $(this).attr("href", "http://" + url);
          }
        });
      });
    })(jQuery)