aldimeola1122
aldimeola1122

Reputation: 818

Javascript query selector

i have a question about javascript selector, i have 3 div elements with same class. and i wwat to change the color of second class.

    <div class="box">
        Element1
    </div>

    <div class="box">
        Element2
    </div>

    <div class="box">
        Element3
    </div>

i've tried following code :

var el = document.body.getElementsByTagName("div")[0].className;
el.style.color = "green";

but it doesn't works.

can you help me? Thanks in advance.

Upvotes: 0

Views: 128

Answers (3)

Domain
Domain

Reputation: 11808

Try this instead to select the second DIV,

    var el = document.body.getElementsByTagName("div")[1];
    el.style.color = "green";

Upvotes: 1

Ian Hazzard
Ian Hazzard

Reputation: 7771

You don't use the .className JS ending. Just use this:

var el = document.body.getElementsByTagName("div")[0];
el.style.color = "green";
<div class="box">
        Element1
    </div>

    <div class="box">
        Element2
    </div>

    <div class="box">
        Element3
    </div>

Upvotes: 1

codebox
codebox

Reputation: 20264

I think you want this:

var el = document.body.getElementsByTagName("div")[0];

adding .className to the end makes el into a string rather than an element.

Also you can omit .body from this is you like, its more usual to just say:

var el = document.getElementsByTagName("div")[0];

Upvotes: 1

Related Questions