JavaScript - Tips'n Tricks - Manipulate a child element by reaching the parent with the getElementsByClassName method of the Document Object

It is sometimes useful to reach a child element with its parent.

Let's see this with an example by using the getElementsByClassName method of the Document Object.

The code below will display an image with a red border.
One second later, the border will be changed in black.

Let's try it:

<!DOCTYPE html>
<style type="text/css">
.theImage1 {
    border: 2px red solid;
.theImage2 {
    border: 2px black solid;

<script type="text/javascript">
    setTimeout('gogo()', 1000);
    function gogo() {
        document.getElementsByClassName('theImage1')[0].parentElement.childNodes[1].className = 'theImage2';

<div id="theDiv">
    <img class="theImage1" src="img/myImage.png"/>

Interesting, isn't it? laugh

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.