www.webdeveloper.com
Results 1 to 4 of 4

Thread: How do I capture the Id of a parent HTML element that won't be known until runtime?

  1. #1
    Join Date
    May 2012
    Posts
    6

    How do I capture the Id of a parent HTML element that won't be known until runtime?

    I have an ASP.NET control that spits out <span> elements and I won't know their Ids until the ASP.NET code is compiled.

    I'm trying to solve this problem using Javascript, using the ParentNode property, but so far I've been unsuccessful.

    Consider this sample Html/Javascript code:

    Code:
    <html>
    <head>
    </head>
    
    <body>
    
    <div id ="mydiv"> some text
    
    	<script type="text/javascript">
    	 var data = document.getElementById('div2').getAttribute('id');
    	alert(data);
    
    </script>
    
    </div>
    </body>
    
    </html>
    Essentially I'm trying to capture the id of the <div> element inside of which the javascript code is located, but I won't know its ID before runtime. I tried code such as document.parentNode.getAttribute('id') and this.parentNode.getAttribute('id') but it did not work.

    Can someone please tell me how to accomplish this?

  2. #2
    Join Date
    Nov 2010
    Posts
    978
    how will this:
    Code:
    document.getElementById('div2').getAttribute('id');
    ever return anything but "div2"?

    you should look at something like
    Code:
    document.getElementById('div2').firstElementChild.id

  3. #3
    Join Date
    Aug 2007
    Posts
    3,767
    You want the parent node's id of this script tag?
    Code:
    var els = document.getElementsByTagName("script"),
      data = els[els.length-1].parentNode.id;
    Last edited by Declan1991; 05-13-2012 at 06:22 PM.
    Great wit and madness are near allied, and fine a line their bounds divide.

  4. #4
    Join Date
    May 2012
    Posts
    6
    Declan, your code does the trick Thanks a lot

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles