Reputation: 13
I would like to print a new line in JS, but I can't figure out how to do it without document.write. I need to do it without this because I'm using buttons to call functions, and when I use doc.write, it erases the page and displays the results of the function on its own.
<h3>$$$$$</h3>
<span id = "$"></span>
<button onclick="prob2()">Submit</button>
<script type="text/javascript">
function prob2(){
n = parseInt(prompt("Enter number: "));
for(var i=0;i<n;i++){
for(var j=0;j<=i;j++){
document.getElementById("$").innerHTML = "$";
}
console.log("\n");
}
};
Rather than having console.log there, I want to print a line break on the screen so that my output looks like this:
$
$$
$$$
...
EDIT: Based on Anurag's first suggestion, I built a string and used it with innerHTML to achieve my desired output.
function prob2(){
var str = "";
var num = parseInt(prompt("Enter number: "));
for(var i=0;i<num;i++){
for(var j=0;j<=i;j++){
str += "$";
}
str += "<br>";
}
document.getElementById("$").innerHTML = str;
};
His second suggestion that I accepted as the answer also works!
Upvotes: 1
Views: 419
Reputation: 14413
Here's one way to do it:
function generate() {
document.getElementById("$").innerHTML = ""
var n = parseInt(prompt("Enter number: ")), str = "", currStr = "";
for (var i = 0; i < n; i++) {
str = "", currStr = document.getElementById("$").innerHTML
for (var j = 0; j <= i; j++) {
str+= "$"
document.getElementById("$").innerHTML = currStr + str + "<br/>";
}
}
};
<h3>Incremental $</h3>
<span id="$"></span>
<button onclick="generate()">Generate</button>
Upvotes: 1
Reputation: 508
I interpreted the question differently. I thought the purpose was to replace the use of the document.write() statement.
<!DOCTYPE html><html lang="en"><head><title> Test Page </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- For: https://stackoverflow.com/questions/62742502/how-can-i-print-a-new-line-in-js-without-using-document-write -->
<style>
p { background-color: lime; }
pre { border: 1px solid red;}
div { border: 3px dotted blue }
</style>
</head><body>
<script>
newLine = (tag,msg) => {
var elem = document.createElement(tag);
elem.appendChild(document.createTextNode(msg));
document.body.appendChild(elem);
// Note: .body. could be a different element or another parameter added to function
}
newLine('p','New line has been created.');
newLine('pre','And then another.');
newLine('div','And then one final new line to display.');
</script>
</body></html>
Remove the CSS styling as it was only added for emphasis.
Upvotes: 1