javascript get child by id

后端 未结 4 1231
广开言路
广开言路 2020-12-13 17:23
Test
child

I want to change the style of the child div

相关标签:
4条回答
  • 2020-12-13 17:44

    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..
    
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-13 17:48

    In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():

    function test(el){
      el.querySelector("#child").style.display = "none";
    }
    

    For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.

    As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").

    0 讨论(0)
  • 2020-12-13 17:48

    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.

    0 讨论(0)
  • 2020-12-13 17:56

    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.

    0 讨论(0)
提交回复
热议问题