0

I am new to JavaScript and I am trying to do something very simple. I wan to appear array[1] text in firstDiv's innerHTML when I click button.

I have followed all instructions but still it's not working.

<!doctype html>
<html>
<head>
    <title>Learning Javascript</title>

    <meta charset="utf-8" />
    <meta htttp-equiv="content-type" contents="text/html; charset-utf8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />  

</head>

<body>

    <button id="stylesChanger">Change the text !</button>

    <div id="firstDiv">This sis some text</div>

    <script type="text/javascript">

        var myArray=new Array[];

        myArray[0]="pizza";
        myArray[1]="chocolate";

        document.getElementById("stylesChanger").onclick=function(){

            document.getElementById("firstDiv").innerHTML=myArray[1];
        }               

        </script

</body>
</html>
4
  • you should try var myArray= new Array(); Commented Mar 14, 2015 at 6:29
  • or var myArray = []; Commented Mar 14, 2015 at 6:30
  • Thank you all. Very quick responses, all correct :) Commented Mar 14, 2015 at 6:50
  • Actually you can see w3school say's myArray=[] is better practice. Commented Mar 14, 2015 at 14:31

2 Answers 2

2

change your var myArray=new Array[]; to var myArray=[];

Then it will work

    var myArray=[];

    myArray[0]="pizza";
    myArray[1]="chocolate";

    document.getElementById("stylesChanger").onclick=function(){

        document.getElementById("firstDiv").innerHTML=myArray[1];
    }
<button id="stylesChanger">Change the text !</button>

<div id="firstDiv">This sis some text</div>

Sign up to request clarification or add additional context in comments.

Comments

0

This code will make sure you get the first element of myArray on button click. And sets the div text as myArray first element.

Working Sample: JSFIDDLE

var myArray = new Array();
myArray[0] = 'pizza';
myArray[1] = 'chocolate';

var btn = document.getElementById('stylesChanger');
btn.addEventListener('click', getArrayFirstElement, false);

function getArrayFirstElement(){
 document.getElementById("firstDiv").innerHTML = myArray[0];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.