Display array elements on the screen

Discussion in 'JavaScript' started by pictureboarduk, Dec 7, 2009.

  1. #1
    Hi,

    I am trying to append some text to a paragraph, and then display it on the screen:


    This is my code:
    
    <html>
    <head>
    </head>
    <body>
    <p id="1">Inside paragraph1</p>
    <p id="2">Inside paragraph2</p>
    <p id="3">Inside paragraph3</p>
    
    <script type="text/javascript">
    	//get all paragraph elements and hold them in the array 'arrayname'
    	var arrayname=document.getElementsByTagName('p');
    
    	arrayname[2].innerText += " some added text";
    	
    	//display new arrayname[2] string
    	document.write(arrayname[2]);
    </script>
    
    </body>
    </html>
    
    Code (markup):
    But instead this is displayed:

    Can anyone see what my error is?

    Thanks for any help!
     
    pictureboarduk, Dec 7, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    you cant document.write the pointer to the element itself. you can write a property of the element, like innerHTML though, so arr[2].innerHTML;

    also, innerText is not in ECMA specification as far as i know (not that innerHTML ever was) but support for innerText cross browser is very poor. use innerHTML instead - and as you append to it, you don't need to write it again.

    element.innerHTML += "bar"; ought to append "bar" if it can read the innerHTML.
     
    dimitar christoff, Dec 7, 2009 IP
    pictureboarduk likes this.
  3. pictureboarduk

    pictureboarduk Well-Known Member

    Messages:
    551
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    140
    #3
    Awesome!

    Worked a treat. never knew about the innerHTML, so will have to read up on that.

    Thanks a lot buddy :)
     
    pictureboarduk, Dec 7, 2009 IP