0

How do you insert an HTML element dynamically (using prototype) at the current position if you don't know the id of the parent element? All examples I've seen assumes the element has some kind of id.

I.e.

<script>
    function addSomeHtmlAtCurrentPosition()
    {
        current_element = ...; // Magic?
        current_element.insert(...);
    }
</script>
<div>
    <script>
        addSomeHtmlAtCurrentPosition();
    </script>
    <!-- should insert something here... -->
</div>
<div>
    <script>
        addSomeHtmlAtCurrentPosition();
    </script>
    <!-- ... and then here -->
</div>

I've tried using prototype with $$('div').last(), but that doesn't seem to work (last() sometimes reports back another div if I use libraries such as livepipe).

What I really want is something similar to document.write, but using prototype instead of raw html.

Rob W
  • 341,306
  • 83
  • 791
  • 678
Christian Genne
  • 190
  • 3
  • 9

1 Answers1

3

The only way I can think of is finding the <script> element and insert the element before/after the script. The thing is, all DOM methods need a DOM node to operate on. Executing scripts that modify the DOM before the document has loaded isn't a good and safe idea.

Similar questions linked below.

  1. JavaScript: get the current executing <script> node?
  2. How may I reference the script tag that loaded the currently-executing script?
Community
  • 1
  • 1
Rafael
  • 18,349
  • 5
  • 58
  • 67
  • 1
    I see, probably makes sense. Modifying an HTML document on the fly is probably a bad idea. In the end I refactored my HTML/javascript to use prototype css selectors to insert HTML elements dynamically, which actually turned out to be a much cleaner solution. – Christian Genne May 15 '11 at 12:19