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>
<html>
<head>
<style type="text/css">
.theImage1 {
    border: 2px red solid;
}
.theImage2 {
    border: 2px black solid;
}
</style>

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

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

Interesting, isn't it? laugh

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.