Skip to content Skip to sidebar Skip to footer

How Do I Replace A Bit Of Text With String Variable In Javascript?

I know this is a really simple question, but I need to replace this bit of text in a paragraph with a variable every time an even fires. The markup looks like this 'http://www.w

Solution 1:

You could create a function that looks something like this.

function replaceTitle (replaceText) {
    document.getElementById("heading").getElementsByTagName("h1")[0].innerHTML = replaceText;
}

If you are using jQuery it could look more like this.

function replaceTitle (replaceText) {
    $("#heading h1").html(replaceText);
}

Then you call the function like this

replaceText(yourVariable);

It would probably be better to give your <h1> tag an id or a class so you can reference it directly, but I am going to assume that you have good reason for not doing so.


Solution 2:

One example on how can be simple things made complicated :)

javascript:

// simple way:
function replace_text(text) {
    var heading = document.getElementById('heading');
    heading.innerHTML = '<h1>' + text + '</h1>';
}

// complicated way:
function replace_text2(text) {
    var heading = document.getElementById('heading');
    var node = heading.childNodes[0];
    while ( node && node.nodeType!=1 && node.tagName!='H1' ){
        //console.log(node.nodeType,node);
        node = node.nextSibling;
    }
    if (node) {
        node.replaceChild(document.createTextNode(text),node.childNodes[0]);
    }
}

html:

<input type="button" onclick="replace_text('HELLO 1!');" value="Replace 1st text" />
<input type="button" onclick="replace_text2('HELLO 2!');" value="Replace 2nd text" />

The script is here.


Post a Comment for "How Do I Replace A Bit Of Text With String Variable In Javascript?"