I'm newbie to JS. I've a code sample below, in which I've written a JS function through which I'm trying to change value of <p>
tag after a button click. My question is why only setting innerHTML
work with getElementById
; but not with the other approaches?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("myid").innerHTML = 'hey';
document.getElementByName("myname").innerHTML = 'Whats';
document.getElementByTagName("p").innerHTML = 'up! ';
document.querySelector("p#myid").innerHTML = 'Dude.';
}
</script>
</head>
<body>
<p id="myid" name="myname">This text will be changed after button click.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Result: I was expecting "Dude." displayed after the click.
Change as follows, it works
document.getElementById("myid").innerHTML = 'hey';
document.getElementsByName("myname")[0].innerHTML = 'Whats';
document.getElementsByTagName("p")[0].innerHTML = 'up! ';
document.querySelector("p#myid").innerHTML = 'Dude.';