Stuck on some code

Discussion in 'JavaScript' started by SEO-Expert, Oct 26, 2010.

  1. #1
    I've adapted a script to change some HTML code when a browser loads, works as expected, but I'm getting a weird bug with a WordPress plugin I'm using and guessing it's easier to change the javascript than fix the plugin :)

    Here's the javascript:

    
    function hasClass(e, c) {
    if (typeof e == "string") e = document.getElementById(e);
    var classes = e.className;
    if (!classes) return false;
    if (classes == c) return true;
    return e.className.search("\\b" + c + "\\b") != -1;
    };
    function affLnks(){
    var theURL, theAnchorText, theTitle, theId;
    var spans = document.getElementsByTagName('span');
    for (var i = 0; i<spans.length; i++){
    if (hasClass(spans[i], 'links')){
    theAnchorText = spans[i].innerHTML;
    theTitle = spans[i].title.toLowerCase().replace(/^\s+|\s+$/g,"");
    theId = spans[i].id.replace(/^\s+|\s+$/g,"");
    switch (theTitle) {
    case 'links': theURL = 'domain.com/'; break;
    default: theURL = '/#';
    }
    spans[i].innerHTML = '<a href="' + theURL + '' + theId + '" class="' + spans[i].className + '">' + theAnchorText + '</a>';
    spans[i].removeAttribute('title');
    }
    }
    }
    window.onload = function(){
    affLnks();
    }
    
    Code (markup):

    HTML with the format

    <span class="links" title="links" id="filename">anchor text</span>
    Code (markup):
    Is converted to a text link.

    The WordPress plugin is stripping the id="filename" part (bug with the plugin). So trying to replace id= with rel=, but I can't get it to work.

    the code I've changed it

    theId = spans[i].id.replace(/^\s+|\s+$/g,"");
    Code (markup):
    to
    theId = spans[i].rel.replace(/^\s+|\s+$/g,"");
    Code (markup):
    but it breaks the script.

    Where am I going wrong?

    David
     
    SEO-Expert, Oct 26, 2010 IP
  2. wing

    wing Active Member

    Messages:
    210
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    58
    #2
    I think you just need to define "rel", and it should work.

    Try this:
    theId = spans[i].getAttribute('rel').replace(/^\s+|\s+$/g,"");
    Code (markup):

    :)
     
    wing, Oct 26, 2010 IP
    SEO-Expert likes this.
  3. SEO-Expert

    SEO-Expert Well-Known Member

    Messages:
    328
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    140
    #3
    Yep, that fixed it, thanks Wing :)

    David
     
    SEO-Expert, Oct 26, 2010 IP