I've got a javascript function 'doAll', which is supposed to write all the text that was put between <p>, </p>
tags. In my code it is used in two ways.
It works correctly when I just call it at the end of the page. However it should also be triggered out when click-button event occurs. For some reason it doesn't do what it is supposed to do this time. When one click on the button it just prints the inner html of the very first <p>...</p>
html element.
My question is why it works differently in these two situations and what should I do to fix this problem.
<!DOCTYPE html>
<html>
<head>
<script>
function returnList(x)
{
return document.getElementsByTagName(x);
}
function writeList(x)
{
var i = 0;
while (x[i])
{
document.write(x[i++].innerHTML + '<br/>');
}
}
function doAll(x)
{
writeList(returnList(x));
}
</script>
</head>
<body>
<p>XXX</p>
<p>YYY</p>
<div style = 'background-color: gray;'>
<p>YYY</p>
<p>XXX</p>
</div>
<button type = 'button' onclick = "doAll('p')">
Click me!
</button>
<script>
document.write('<br/>');
doAll('p');
</script>
</body>
</html>
Here is the 'output':
XXX
YYY
YYY
XXX
XXX
YYY
YYY
XXX
And here is what one can see after clicking the button:
XXX