使用具有特定ID的DIV内的JavaScript动态添加HTML元素 [英] Add HTML elements dynamically with JavaScript inside DIV with specific ID

查看:603
本文介绍了使用具有特定ID的DIV内的JavaScript动态添加HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我需要你的帮助。我在Stackoverflow上找到了一些代码(无法找到那个链接),它通过JS动态生成HTML代码。这是代码:

Ok, poeple, I need your help. I've found some code here on Stackoverflow (can't find that link) which generate HTML code dynamically via JS. Here is code:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
      }
        return frag;
    }

    var fragment = create('<div class="someclass"><a href="www.example.com"><p>some text</p></a></div>'); 

    document.body.insertBefore(fragment, document.body.childNodes[0]);

此代码工作正常!但生成的代码位于页面顶部,位于 body 标记的正下方。我的愿望是使用特定的 id =generate-here在空 div 中生成该代码。

This code work's just fine! But generated code apears on top of page, right below body tag. My wish is to generate that code inside empty div with specific id="generate-here".

因此输出将是:

<div id="generate-here">
    <!-- Here is generated content -->
</div>

我知道我看不到带有查看源的生成内容。我只需要在#generate-here 的特定位置生成该内容。我是Javascript noob,所以如果有人可以重新排列这个完美的代码。非常感谢!

I know that I can't see generated content with "view source". I only need to generate that content just in this particular place with #generate-here. I'm Javascript noob, so if anyone can just rearrange this code that will be perfect. Thanks a lot!

P.S。我知道如何用Jquery做到这一点,但在这种情况下我需要原生和纯JavaScript。

P.S. I know how to do this with Jquery, but I need native and pure JavaScript in this case.

推荐答案

你需要做的一切是改变最后一行。这会将创建的元素添加为div的 last 子元素:

All you need to do is change the last line. This will add the created element as the last child of the div:

document.getElementById("generate-here").appendChild(fragment);     

这会将创建的元素添加为div的第一个子元素:

This will add the created element as the first child of the div:

var generateHere = document.getElementById("generate-here");
generateHere.insertBefore(fragment, generateHere.firstChild);

您还可以使用innerHTML替换所有新文本(就像在<$ c中一样) $ c> create function)。显然,这个不需要你保留 create 函数,因为你需要一个html字符串而不是一个DOM对象。

You can also use innerHTML to just replace everything with new text (as you do in your create function). Obviously this one doesn't require you to keep the create function because you need an html string instead of a DOM object.

var generateHere = document.getElementById("generate-here");
generateHere.innerHTML = '<div class="someclass"><a href="www.example.com"><p>some text</p></a></div>';

这篇关于使用具有特定ID的DIV内的JavaScript动态添加HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆