JavaScript Trying to replace content in all anchors, but content not being replaced

I am trying to replace all the content, depending on what it is, with a corresponding unicode character in all anchors that are descendants of the class nav ( .nav a ).

But this javascript / jQuery doesn't seem to be doing anything.

It is not showing any errors, just nothing is happening.

What am I doing wrong and how can I replace certain text with other certain text with javascript / jQuery ?

Here is the code:

$(document).ready(function(){
    var navigationLinks = $('.nav a');
for(var i=0; i < navigationLinks.length; i++){
    var thisLink = navigationLinks.eq(i);
    switch(thisLink.html()){
        case "About":
            thisLink.html().replace(/About/g,'&#xe00f;');

        case "Work":
            thisLink.html().replace(/Work/g,'&#xe010');

        case "CV":
            thisLink.html().replace(/CV/g,'&#xe00c');

        case "Resume":
            thisLink.html().replace(/Resume/g,'&#xe00d;');

        case "down":
            thisLink.html().replace(/down/g,'&#xe00d;');

        case "Mail":
            thisLink.html().replace(/Mail/g,'&#xe011;');

        case "Dribbble":
            thisLink.html().replace(/Dribbble/g,'&#xe015;');

        case "GooglePlus":
            thisLink.html().replace(/GooglePlus/g,'&#xe012;');

        case "Facebook":
            thisLink.html().replace(/Facebook/g,'&#xe013;');

        case "Twitter":
            thisLink.html().replace(/Twitter/g,'&#xe014');

        default:
            thisLink.html().replace(thisLink.html(),thisLink.html());
    }
}
});

And here is a live example of the code where I tried it, but it doesn't work. The text inside the anchors inside the .nav class is still the original text and not the unicodes: https://dl.dropboxusercontent.com/u/270523/help/replace/index.html

Answer:1

html() gets the innerHTML, while html("string") sets the innerHTML. You have to re-set the value; you can't just call replace on a string.

As an example, you can redo your case statements to follow this convention:

var myHtml = thisLink.html();
switch (myHtml) {
    case "About":
        thisLink.html(myHtml.replace(/About/g, '&#xe00f;'));
        break;

or use this for the .html() call:

thisLink.html(function (i, oldVal) {
    return oldVal.replace(/About/g, '&#xe00f;');
});

Also, you need to include break for each case, to prevent the next block from executing.

In addition, the jQuery way to loop through the matched elements is with .each(), not a for loop (although still very valid). So something like:

$('.nav a').each(function () {
    var thisLink = $(this);
    var myHtml = thisLink.html();
    // The rest of the code...
});
Answer:2

Demo: http://jsfiddle.net/7hKTs/

Note that you could do this more concisely, but I wanted to retain your original structure so that you could see the corrections I made in context.

  • Added breaks in the switch statement.
  • Added proper assignment of html after replace(). html() is a method; you need to do something with its return value (such as assign it to a variable).

Example 1: thisLink.html().replace(/About/g,'&#xe00f;');. This gets the HTML of the link, calls replace() on it, but the return value of replace() is unused. This will not have the desired effect.

Example 2: thisLink.html(thisLink.html().replace(/About/g,'&#xe00f;')); This now passes the modified HTML to the html() method. In this single line, it both gets and sets the HTML by calling html() with and without arguments.

Example 3: However, example #2 is very verbose/repetitive when used multiple times, so we can do something simpler:

// get the value
var html = thisLink.html();

// handle any number of cases here

// note the assignment of the return value of html()
html = html.replace(/About/g, '&#xe00f;');

// set the value
thisLink.html(html);

See also: http://api.jquery.com/html/

Full Example

$(document).ready(function () {
    var navigationLinks = $('.nav a');
    for (var i = 0; i < navigationLinks.length; i++) {
        var thisLink = navigationLinks.eq(i);
        var html = thisLink.html();

        switch (html) {
            case "About":
                html = html.replace(/About/g, '&#xe00f;');
                break;
            case "Work":
                html = html.replace(/Work/g, '&#xe010');
                break;
            case "CV":
                html = html.replace(/CV/g, '&#xe00c');
                break;
            case "Resume":
                html = html.replace(/Resume/g, '&#xe00d;');
                break;
            case "down":
                html = html.replace(/down/g, '&#xe00d;');
                break;
            case "Mail":
                html = html.replace(/Mail/g, '&#xe011;');
                break;
            case "Dribbble":
                html = html.replace(/Dribbble/g, '&#xe015;');
                break;
            case "GooglePlus":
                html = html.replace(/GooglePlus/g, '&#xe012;');
                break;
            case "Facebook":
                html = html.replace(/Facebook/g, '&#xe013;');
                break;
            case "Twitter":
                html = html.replace(/Twitter/g, '&#xe014');
                break;
        }

        thisLink.html(html);
    }
});

Alternative

Demo: http://jsfiddle.net/7hKTs/5/

I like this approach better because it takes the markup almost completely out of the script. Instead, we use data-* attributes to store the alternative HTML string.

HTML

<nav class="nav">
    <ul>
        <li><a target='_blank' href="#" data-alt="&#xe00f;">About</a></li>
        <li><a target='_blank' href="#" data-alt="&#xe010;">Work</a></li>
        <li><a target='_blank' href="#" data-alt="&#xe00c;">CV</a></li>
        <!-- etc -->
    </ul>
</nav>

JavaScript

$(document).ready(function () {
    $('.nav a').each(function () {
        var obj = $(this);
        obj.html(obj.data("alt"));
    });
});
Answer:3

Given that switch/case work with exact matches already, the global RegExp and replace are actually repeating work:

switch(thisLink.html()){
    case "About":
        thisLink.html('&#xe00f;');
        break;

    case "Work":
        thisLink.html('&#xe010;');
        break;

    // etc.
}
Answer:4

I believe it would be far easier to work with a replacement map and iterate over each anchor using .each():

$(document).ready(function() {
    var navigationLinks = $('.nav a'),
    replacements = {
        "About": '&#xe00f;',
        "Work": '&#xe010',
        "CV": '&#xe00c',
        "Resume": '&#xe00d;',
        "down": '&#xe00d;',
        "Mail": '&#xe011;',
        "Dribbble": '&#xe015;',
        "GooglePlus": '&#xe012;',
        "Facebook": '&#xe013;',
        "Twitter": '&#xe014'
    };

    navigationLinks.each(function() {
        var $this = $(this),
        txt = replacements[$this.text()];

        if (txt) {
            $this.text(txt);
        }
    });
});
Answer:5

Can anyone please help me how to do this? I would like to pass the message from the websocket to the serial port every time I receive a message var firmata = require('firmata'); var board = new ...

Can anyone please help me how to do this? I would like to pass the message from the websocket to the serial port every time I receive a message var firmata = require('firmata'); var board = new ...

  1. javascript message passing
  2. javascript message passing between windows

Is it possible to include JQuery in the here-doc section of perl. I tried but no success. Here is my code. my $cgi = CGI->new();print header();print start_html("JQuery in perl"); print <<JS;...

Is it possible to include JQuery in the here-doc section of perl. I tried but no success. Here is my code. my $cgi = CGI->new();print header();print start_html("JQuery in perl"); print <<JS;...

This is a basic html/javascript code, but I am having issues getting the sum of all fields. (The are 50 fields in the original project, but now I just leave 5) If the field is blank, it just has to ...

This is a basic html/javascript code, but I am having issues getting the sum of all fields. (The are 50 fields in the original project, but now I just leave 5) If the field is blank, it just has to ...

  1. issue fields in jira
  2. issue.fields
  3. http://issue.fields.issuetype.name
  4. issue.fields jira python
  5. issue.fields.customfield
  6. issue.fields.issue links
  7. issue.fields.summary
  8. issue.fields.assignee
  9. issue.fields.status
  10. issue.fields.description
  11. issue fields jira api
  12. issue.fields.worklog.worklogs
  13. issue.fields.issuetype
  14. issue.fields.components
  15. issue.fields.comment
  16. issue.fields.priority
  17. issue.fields.labels
  18. issue.fields.customfield python
  19. issue.fields.project.key
  20. issue.fields.time tracking

This is the code when i am adding in all textbox it works fine but after removing number it shows NaN function sumVal() { var total = 0; var coll = document.getElementsByTagName("input") ...

This is the code when i am adding in all textbox it works fine but after removing number it shows NaN function sumVal() { var total = 0; var coll = document.getElementsByTagName("input") ...