3

This code would speak for it self and explain what I'm trying to achieve...

<style>
.red{background:red}
.blue{background:blue}
</style>

<div id=test>
    <button>1</button>
    <button>2</button>
</div>

<script>
var firstBtn=document.getElementById("test").firstChild.className;

(firstBtn!="red")?firstBtn="red":firstBtn="blue";
</script>

Here is the jsFiddle : http://jsfiddle.net/hnfeje2q/

Very simple but since I'm new to JavaScript...

Thanks!

davidmarko
  • 343
  • 3
  • 17
  • `firstElementChild` is a more reliable and useful version of `firstChild`. It will ignore any text node. – Touffy Apr 02 '15 at 12:23

4 Answers4

2

document.getElementById("test").firstChild is not a reference to the first button as you might expect, but to a text node (that is the space between the open <div id="test"> tag and the first button element.

use instead document.querySelector('#test button:first-child') to get a reference to the first button element

var firstBtn = document.querySelector('#test button:first-child');
firstBtn.className = (firstBtn.className !== "red")? "red" : "blue";
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
2

You can first get the div wrapper with id=test and then load the first child element inside that wrapper with the code below and then you can add the class 'red' to that element/button.

var wrapper = document.getElementById("test");
var firstButton = wrapper.childNodes[1];

// if the button doesn't have a red class, set it
if(firstButton.className.indexOf('red') == -1) {
    firstButton.className = firstButton.className + ' red';
}

or go with the query selector

var firstButton = document.querySelector('#test button:first-child');
if(firstButton && firstButton.className.indexOf('red') == -1) {
    firstButton.className = firstButton.className + ' red';
}
Tim Rijavec
  • 1,770
  • 22
  • 27
  • .childNodes[1] is the second child element, not the first one – Fabrizio Calderan Apr 02 '15 at 12:31
  • @FabrizioCalderan .childNodes[1] is the same as .children[0], element node, but .childNodes[0] is a text node and not element node. You can find out more about node types [here](http://www.w3schools.com/jsref/prop_node_nodetype.asp). – Tim Rijavec Apr 02 '15 at 13:28
1

Updated jsfiddle

var firstBtn = document.querySelector('#test button:first-child');

if (firstBtn !== "red") {
    firstBtn.className = "red";
} else {
    firstBtn.className = "blue";
}
br3w5
  • 4,403
  • 5
  • 33
  • 42
1

Instead of using firstChild, use childNodes. Also, firstBtn is simply going to be a string with the name of the class. To change it, you actually need to set the className on the button using a similar syntax.

var firstBtn=document.getElementById("test").childNodes[1].className;
(firstBtn!="red")?document.getElementById("test").childNodes[1].className="red":document.getElementById("test").childNodes[1].className="blue";
Grundy
  • 13,356
  • 3
  • 35
  • 55
Troy
  • 146
  • 4