I am a learner to JS and while learning i was trying to append same text in multiple tags for html. For example if i had a "h1" tag that i want to insert inside multiple html tags like header,section,article,p etc.
I thought to do it by JS but while doing so it happens that if i append two different text in multiple tag it works fine which can be seen by clicking Button 2 the text with color:red gets append in p tag with id="output" & other text in p tag with id ="output2"
But while clicking Button 1 i am appending same text in both p tag but it only gets append in p tag with id ="output2".
What's the reason for that ?
Note:
Although i said i want to append the text but my initial thought was to do it completely by JS thats why i am creating element and then text node and then appending it in HTML
function temp() {
var h1 = document.createElement("h1");
var text = document.createTextNode("Heading 1");
h1.appendChild(text);
var h2 = document.createElement("h2");
var text2 = document.createTextNode("Heading 2");
h2.appendChild(text2);
document.getElementById("output").appendChild(h1);
document.getElementById("output2").appendChild(h2);
}
function main() {
var h1 = document.createElement("h1");
var text = document.createTextNode("Heading 1");
h1.appendChild(text);
document.getElementById("output").appendChild(h1);
document.getElementById("output2").appendChild(h1);
}
<!DOCTYPE html>
<html>
<head>
<style>
#output {
color: red;
}
</style>
</head>
<title>
XYZ
</title>
<body>
<button onclick="main()">Button 1</button>
<button onclick="temp()">Button 2</button>
<p id="output">
</p>
<p id="output2">
</p>
</body>
</html>