使用getElementById复制页面中的内容

时间:2013-09-25 14:50:35

标签: javascript html

我不知道javascript,我一直在寻找这个答案的每个地方。我想在我的页面中复制内容。 html和内容直接来自经纪人。

想要的结果是:

Click the button to change the text in this paragraph.
Click the button to change the text in this paragraph.

我的HTML是:

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
var elem = document.getElementById('demo').setAttribute('id', 'nextstep');
document.write(elem);
</script>
</body>
</html>

我得到的是:

Click the button to change the text in this paragraph.
undefined

有人能指点我正确的方向吗?提前谢谢!

5 个答案:

答案 0 :(得分:3)

我不相信你想要使用document.write。我认为这就是你所追求的目标:

<script language="javascript" type="text/javascript">
    // this gets the element
    var elem = document.getElementById('demo'); 
    // this copies the entire element, including the id
    var newElem = elem.cloneNode(true); 
    // this sets a new id
    newElem.setAttribute('id', 'nextstep');
    // generic way to make sure you insert properly
    var before = elem.nextSibling;
    // there's no insertAfter, only insertBefore, which is why we found the before
    elem.parentNode.insertBefore(newElem, before);
</script>

FIDDLE

答案 1 :(得分:1)

你需要抓住innerHTML并设置它:

var elem = document.getElementById('demo').innerHTML;
document.write(elem);

请注意,document.write将覆盖所有内容。

答案 2 :(得分:1)

您将elem设置为setAttribute的返回值,该值未定义,因为它不返回任何内容。

将代码更改为:

var elem = document.getElementById('demo');
elem.setAttribute('id', 'nextstep');
document.write(elem.innerHTML);

示例 - http://jsfiddle.net/P8EcL/

这仍然不会完全符合您的要求,因为它是p标签内容的副本而不是标签本身。

Scott Mermelstein's回答是你想要的。

答案 3 :(得分:1)

如果你需要这个

<p id="demo">Click the button to change the text in this paragraph.</p>
<p id="nextstep">Click the button to change the text in this paragraph.</p>

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
    var elem = document.getElementById('demo');
    var newElem = document.createElement('div');
    newElem.innerHTML = "<p id='nextstep'>" + elem.innerHTML + "</p>";
    document.write(newElem.innerHTML);
</script>
</body>
</html>

答案 4 :(得分:0)

var elem = document.getElementById('demo').innerHTML;
document.write(elem);

我不确定你为什么要尝试在原始div上设置一个新的id并期望它返回HTML,但它不会起作用;)