Page 1 of 1

Help! basic JS function problem

Posted: Wed Dec 14, 2011 8:46 pm
by axlemax
In the following code I have a script and then I want to run the same script as a function that is called by pressing the button. But the function doesn't work. Can you help me to understand why please?

<!DOCTYPE html>
<html>

<head><title></title></head>

<body>

<img src="klematis.jpg" width="150" height="113" />
<img src="klematis2.jpg" width="152" height="128" />


<script type="text/javascript">
function show_images(){
var imgs = document.getElementsByTagName('img');

if(imgs.length > 0){
for(var i=0; i<imgs.length; i++){
document.write("The source of image object ",(i+1));
document.write('<br />');
document.write(imgs.src);
document.write('<br />');
}
}
}
</script>

<script type="text/javascript">

var imgs = document.getElementsByTagName('img');

if(imgs.length > 0){
for(var i=0; i<imgs.length; i++){
document.write("The source of image object ",(i+1));
document.write('<br />');
document.write(imgs.src);
document.write('<br />');
}
}

</script>


<input type="button" onclick="show_images()" value="Show images" />


</body>
</html>

Re: Help! basic JS function problem

Posted: Wed Dec 14, 2011 9:41 pm
by McInfo
The code outside the function runs while the document is loading. That is, it runs after the document has been opened but before "</html>" has been written. You could call the show_images() function in place of that code and notice no difference in the output.

The problem with calling the function via a button is that the function then runs after the document has been closed. Calling document.write() at that point implicitly calls document.open() to reopen and clear the document.

An alternative approach is to modify the innerHTML of an existing element, or use document.createTextNode() and document.body.appendChild().

Re: Help! basic JS function problem

Posted: Wed Dec 14, 2011 11:19 pm
by axlemax
OK. So I am trying to follow your advice and learn how to use createTextNode and appendChild
(Firefox with JS enabled).
Why isn't this working please?

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">

function editNodeText(id, newText)
{
var node = document.getElementById(id);

while (node.firstChild)
node.removeChild(node.firstChild);

node.appendChild(document.createTextNode(newText));
}

</script>
</head>
<body>

<span id=”spanEx” onclick="editNodeText('spanEx','New text is here')">Change this text</span>

</body>

</html>

Re: Help! basic JS function problem

Posted: Fri Dec 16, 2011 9:19 am
by McInfo
Be careful with the quote characters.

Code: Select all

<span id=”spanEx”
<span id="spanEx"