0
<!DOCTYPE html>
<html>
<head>
<script>

function changetext(mypara)
{
    mypara.innerHTML="Ooops!";
}
</script>
</head>
<body>
<script>var mypara = document.getElementById("para1");</script>
<h1 onclick="changetext(mypara)">Click this text to change the content of following   paragraph</h1>
<p id="para1"> this is a paragraph I would like to change </p>

</body>
</html>

I would like to let user to click the heading to change the content of the paragraph, but I don't know the correct way of coding that. How to send the "mypara" parameter to myFunction() in HTML?

2 Answers 2

1

Your example almost works - the problem is when you execute this line:

var mypara = document.getElementById("para1");

The element you're refering to does not yet exist. You could fix it by just going inline:

<h1 onclick="changetext(document.getElementById('para1'))">...</h1>

Live example for this approach: http://jsfiddle.net/Gw5CG/2/

or perhaps just pass the id to the method:

<h1 onclick="changetext('para1')">...</h1>

and change the method to do the getElementById:

function changetext(mypara)
{
    document.getElementById(mypara).innerHTML="Ooops!";
}

Live example for this approach: http://jsfiddle.net/Gw5CG/1/

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

1 Comment

Jamiec, you are really very helpful! Thank you!
0

The element doesn't exist yet when you're trying to get it.
Why not just get it in the event handler

<!DOCTYPE html>
<html>

    <head>
        <script>
            function changetext() {
                document.getElementById("para1").innerHTML = "Ooops!";
            }
        </script>
    </head>

    <body>
        <h1 onclick="changetext()">Click this text to change the content of following   paragraph</h1>

        <p id="para1">this is a paragraph I would like to change</p>
    </body>

</html>

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.