Is there a simple Javascript command that targets another object?

I have a page with two divs in it, one inside the other, for example:

<div id='one'> <div id='two'></div> </div> 

I want div one to change the class when it is clicked, and then change it when div 2 is selected.

I am completely new to javascript, but I managed to find a simple command that makes the div one change when I click on it.

 <div id='one' class='a' onclick="this.className='b';"> <div id='two'></div> </div> 

Now I just need an equally simple way to change div one back when I click on the number.

I tried changing "this.className" to "one.classname" and for some reason worked when I was working with images, but it doesn’t work with divs at all

 <div id='one' class='a' onclick="this.className='b';"> <div id='two' onclick="one.className='a';"> This does not work. </div> </div> 

Essentially, I am wondering if there is a javascript "this" replacement that I can use to target other elements.

I found several scripts that will perform the action I'm looking for, but I don't want to use a huge, long, complex script if there is another simple one, like the first one I found.

+4
source share
3 answers

You can use document.getElementById

 <div id='two' onclick="document.getElementById('one').className='a'; return false;"> This does not work. </div> 
+4
source

This will work:

 document.getElementById('one').className = 'a'; 
+3
source

you can get the element by id with:

 document.getElementById("one") 
0
source

All Articles