0

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.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#container {width:100%; text-align:center; }
#heading {width:100%; text-align:center; }
</style>
</head>

<div id="heading">
<h1>hello</h1> 
</div> 
<body>
<div id="container">
<textarea name="mytextarea" cols="60" rows="40"></textarea>
</div>
</body>
</html>

What I need is where it says "hello" in the tags, is for that to be a variable that van be replaced by a string that I will generate.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.