Javascript replace and append child

mikeLspohn picture mikeLspohn · Sep 9, 2014 · Viewed 8.8k times · Source

Im having trouble figuring out how to change a word in an included paragraph in a html file. I need to change the use the replace function to replace one word, then append a new paragraph with the paragraph that has the newly replaced word. I've tried multiple things, here's what I have right now.

function replace(){
var str = document.getElementById('para').innerHTML;
var wat = str.replace("ipsum", "World");
var el = document.createChild('p');
document.getElementById('para').innerHTML = wat;
el.innerHTML = wat;
document.body.appendChild('el');
}

replace();

I do not even need it all in a function, I just recently added that because nothing else I was doing was working.

Answer

T.J. Crowder picture T.J. Crowder · Sep 9, 2014

There are various issues here, but the biggest is this:

var el = document.createChild('p');

There is no document.createChild function, so that's throwing an error, preventing any of your other code from running. That's why you don't see the text of para get updated, your assignment to its innerHTML is after that line.

It's unclear why you're creating a new element if your goal is to update the text in para, you can just do this:

function replace(){
    var str = document.getElementById('para').innerHTML;
    var wat = str.replace("ipsum", "World");
    document.getElementById('para').innerHTML = wat;
}

replace();

Note that when you pass replace a string for the first argument, only the first instance will be replaced, so for instance "lorem ipsum lorem ipsum" will become "lorem World lorem ipsum". If you want to replace all of them, use a regular expression with the g ("global") flag:

var wat = str.replace(/ipsum/g, "World");

If you do want to create an append a child, the function to create it is createElement, and you append without the quotes:

var el = document.createElement('p'); // <= createElement, not createChild
// ...
document.body.appendChild(el);        // <= No quotes

From a comment you made on the question:

I want to keep the original paragraph there, and then add another one with the original using the replaced word.

Okay, so then you don't want to update para's innerHTML, you want to set el's innerHTML instead:

function replace(){
    var str = document.getElementById('para').innerHTML;
    var el = document.createElement('p');
    el.innerHTML = str.replace("ipsum", "World"); // Or possibly using /ipsum/g
    document.body.appendChild(el);
}