0

I want to get the ID of a div using JavaScript that runs inside that div. I want to appendChild() html to that div.

eg:

<div id="randomnumber">
<script type="text/javascript"> 
var htmlcontent = "abcdf";
//need the id of div holder
var thisDIVid= ?????;
// appendChild to this div
?????.appendChild(htmlcontent);
</script>
</div>
gariepy
  • 3,576
  • 6
  • 21
  • 34
Binh Nguyen
  • 1,313
  • 3
  • 17
  • 27

2 Answers2

0

If you know where in the structure your div is placed you can access it like this:

var mainDiv = document.getElementById('mainDiv');
yourDiv = mainDiv.getElementsByTagName('div')[number];

number is the place in the structure

Jacob
  • 3,580
  • 22
  • 82
  • 146
-2

document.getElementyById("yourDivId"); will find any div with an unique ID.

var div = document.getElementyById("yourDivId");
div.appendChild("yourContent");
Jacob
  • 3,580
  • 22
  • 82
  • 146
  • thanks.. but the id of div created by other script which is random .. so i need get it from script running inside that div, the point is.. i need to use appendChild to write some code html in that div but can not do without knowing id of this div... – Binh Nguyen Feb 26 '13 at 09:15
  • If you include your script the you can set id to somekind of a global variable. – Jacob Feb 26 '13 at 09:20
  • the id created by php from server.. :( – Binh Nguyen Feb 26 '13 at 09:53
  • Then search here: http://stackoverflow.com/questions/415868/get-variable-from-php-to-javascript – Jacob Feb 26 '13 at 09:55
  • thanks.. but was thinking about that, but not work on my case :) only way is javascript detect id of div element which hold it. – Binh Nguyen Feb 26 '13 at 10:19
  • Then use parentNode. 'myElem.parentNode;' – Jacob Feb 26 '13 at 10:22
  • I can not make this work.. could you help.. thanks
    – Binh Nguyen Feb 26 '13 at 11:20
  • You can find divs by className and then If you now where in your HTML structure it is paste the content there. – Jacob Feb 26 '13 at 11:36