[javascript] javascript get child by id

<div onclick="test(this)">
    Test
    <div id="child">child</div>
</div>

I want to change the style of the child div when the parent div is clicked. How do I reference it? I would like to be able to reference it by ID as the the html in the parent div could change and the child won't be the first child etc.

function test(el){
  el.childNode["child"].style.display = "none";
}

Something like that, where I can reference the child node by id and set the style of it.

Thanks.

EDIT: Point taken with IDs needing to be unique. So let me revise my question a little. I would hate to have to create unique IDs for every element that gets added to the page. The parent div is added dynamically. (sort of like a page notes system). And then there is this child div. I would like to be able to do something like this: el.getElementsByName("options").item(0).style.display = "block";

If I replace el with document, it works fine, but it doesn't to every "options" child div on the page. Whereas, I want to be able to click the parent div, and have the child div do something (like go away for example).

If I have to dynamically create a million (exaggerated) div IDs, I will, but I would rather not. Any ideas?

This question is related to javascript

The answer is


document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.

edit : see this page - ids MUST be unique.

edit edit : alternate way to solve the problem :

<div onclick="test('child1')">
    Test
    <div id="child1">child</div>
</div>

then you just need the test() function to look up the element by id that you passed in.


This works well:

function test(el){
  el.childNodes.item("child").style.display = "none";
}

If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.


If the child is always going to be a specific tag then you could do it like this

function test(el)
{
 var children = el.getElementsByTagName('div');// any tag could be used here..

  for(var i = 0; i< children.length;i++)
  {
    if (children[i].getAttribute('id') == 'child') // any attribute could be used here
    {
     // do what ever you want with the element..  
     // children[i] holds the element at the moment..

    }
  }
}