Why is replace() disrupting onclick()?

I am using replace to search my dynamically loaded webpage for this symbol Æ and replace it with ®. I found the code to do so in this question: Find and replace specific text characters across a document with JS

    $("body").children().each(function () {
            $(this).html( $(this).html().replace(/Æ/g,"®") );
    });

However, after I added this code, this function stopped working.

    document.getElementById("backToClasses").onclick = function() {
        console.log("Clicked");
    };

Can anyone tell me why this might happen?

Answers:

Answer

In the second chunk of code (which I assume runs first) you are locating an element in the DOM and assigning a value to a property of it.

The first chunk of code goes over the DOM and converts large chunks of it into HTML source code, it then modifies that source code, then it generates new DOM elements from it and replaces whatever was there before with them.

So the element with the ID backToClasses:

  1. Gets a click handler
  2. Is converted to HTML
  3. Is destroyed
  4. Is replaced by a new version created from its old HTML

The click handler was only ever on the DOM, so the new element doesn't have it.


If you are going to take this approach, then you should look at looping over just the text nodes in the document and dealing in text rather than HTML. To do that you'll need to recursively loop over the DOM and test the node type of each element.

It would be better to fix the underlying problem that you are hacking around though. It is almost certainly down to an incorrectly specified character encoding somewhere.

The W3C has some material on character encodings that might be helpful.

Answer

By doing this:

$("body").children().each(function () {
        $(this).html( $(this).html().replace(/Æ/g,"®") );
});

You re-create all the HTML elements, so any events that you might have bound before are lost. Don't use the .html() function to replace text. And still, I'm not sure that this is the best way to replace a character.

This replace should be done server-side, not client side. By doing it client-side (in JavaScript) you can get into different problems like SEO (Google indexing your site with your badly encoded characters). If the characters are like this inside a file, simply replace them in that file, make sure to save the file with the right encoding.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.