Reputation: 3384
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.
Upvotes: 2
Views: 1196
Reputation: 12028
The script fails on the document.getElementByName("myname").innerHTML = 'Whats';
line, because getElementByName
is not a function, and it errors when the script tries to call it. The correct name is getElementsByName
; elements. Same for getElementsByTagName
.
Also, both functions return lists of elements and not single elements. Because of that, here, you want to use [0]
to get the first element in that list, then work with it that way:
document.getElementsByName("myname")[0].innerHTML = 'Whats';
Use F12 or Ctrl+Shift+I (depending on the browser) to open up your browser console to see errors, and consult the documentation (from the site I linked for example) to make sure you're using the right function.
Upvotes: 4
Reputation: 1325
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.';
Upvotes: 2
Reputation: 1006
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
debugger;
document.getElementById("myid").innerHTML = 'hey';
document.getElementsByName("myname").innerHTML = 'Whats';
document.getElementsByTagName("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>
Here you have wrote document.getElementByName("myname").innerHTML = 'Whats'; which is not correct it must be document.getElementsByName("myname").innerHTML = 'Whats'; Try this It works. FYI document.getElementsByName return array of elements with same name .
Upvotes: 2
Reputation: 228
I'm sure document.querySelectorAll
, document.getElementsByClassName
and document.getElementsByTagName
will return a NodeList object. However, document.querySelector
should return the first match of that element within the given context (document).
Upvotes: 1