1

I'm trying to create a button that when clicked, creates a carriage return. For example, at the top of my webpage there are buttons that output words when clicked. Upon the click of the next button, the new word is placed immediately after the other words. I need this button to create a new line for the output words above it. I've tried a few codes along the lines of this:

<input type="button" value="Return"
onclick="document.getElementById('outputDiv').innerHTML=
document.getElementById('outputDiv').innerHTML + \br;">
<div id="outputDiv"></div>

Any help would be greatly appreciated.

1 Answer 1

1

Try to avoid using .innerHTML, instead consider the DOM methods of node.appendChild and document.createElement

function newline() {
    document.getElementById('outputDiv').appendChild(
        document.createElement('br')
    );
}
// after input exists, select it with your favourite method to attach listener
document.querySelector('input[value="Return"]').addEventListener(
    'click',
    newline
);

When attached this way the HTML doesn't need an onclick attribute anymore either

<input type="button" value="Return" />
<div id="outputDiv"></div>

DEMO

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

1 Comment

I'm still having some issues implementing this. I've been editing this coding now, and just need to figure out how to achieve the output. <script> var btn = document.createElement("BUTTON"); var t = document.createTextNode("Return"); btn.appendChild(t); document.body.appendChild(btn); </script>

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.