如何使用原型在HTML中的当前位置插入元素

问题描述:

如果您不知道父元素的ID,那么如何在当前位置动态插入HTML元素(使用原型)?我看到的所有例子都假定这个元素有一些id。

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.

Ie

<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>

我已经尝试使用带有$$('div')的原型last(),但是似乎没有工作(last()有时报告另一个div如果我使用库,如livepipe)。

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).

我真正想要的是类似于document.write ,但是使用原型而不是raw html。

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

我想到的唯一方法是找到< script>元素并在脚本之前/之后插入元素。事情是,所有DOM方法都需要一个DOM节点来操作。在文档加载之前执行修改DOM的脚本不是一个好的安全思路。

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.

以下链接的类似问题。


  1. JavaScript:获取当前执行的&LT;脚本&GT;节点?

  2. 如何引用加载当前执行脚本的脚本标签?

  1. JavaScript: get the current executing <script> node?
  2. How may I reference the script tag that loaded the currently-executing script?