SPN
SPN

Reputation: 67

How to change 3rd Div backgroundColor using Javascript

I have 5 div. There is not ID or Class on it. I have to change background color of 3rd div. I try with below, please let me know what went wrong here.

 <div>Div sample content</div>
    <div>Div sample content</div>
    <div>Div sample content</div>
    <div>Div sample content</div>
    <div>Div sample content</div>

Javascript

    <input type="button" onclick="getValue()" value="Click"/>

function getValue()
        {
            var result = document.getElementsByTagName('div');

    alert(result.length);
            result[4].style.backgroundcolor ="red";
        }

Upvotes: 0

Views: 70

Answers (3)

Manwal
Manwal

Reputation: 23836

Try this:

result[2].style.backgroundColor ="red";
       ^-third            ^-capital

DEMO

Upvotes: 1

Tushar Gupta
Tushar Gupta

Reputation: 15923

To change the color of the 3rd div use result[2] and the capitalize the C in backgroundColor

function getValue()
        {
            var result = document.getElementsByTagName('div');

    alert(result.length);
            result[2].style.backgroundColor ="red";
        }
 <div>Div sample content</div>
    <div>Div sample content</div>
    <div>Div sample content</div>
    <div>Div sample content</div>
    <div>Div sample content</div>


    <input type="button" onclick="getValue()" value="Click"/>

Upvotes: 1

error
error

Reputation: 756

Try capitalizing the c in backgroundColor.

Upvotes: 0

Related Questions