javascript 如何将两个div合并为一个div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15005571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:07:16  来源:igfitidea点击:

How To merge two divs to one div

javascriptjqueryhtml

提问by user2095956

I have two divs

我有两个div

<div id = "first">some details111</div>

and

<div id = "second">some details222</div>

I want to create:

我想创建:

<div id ="New">some details111 some details222</div>

What is the best and the fast way to do it?

最好和最快的方法是什么?

回答by red_alert

Using jQuery you could do that:

使用 jQuery 你可以做到:

$(document).ready(function(){
   $("body").append("<div id='New'></div>");
   $("#New").text($("#first").text() + " " +$("#second").text());
});

回答by Nick Tomlin

Some vanilla JS for kicks and giggles:

一些用于踢腿和咯咯笑的香草 JS:

// grab the content from our two divs
var content1 = document.getElementById('one').innerHTML;
var content2 = document.getElementById('two').innerHTML;

// create our new div, pop the content in it, and give it an id
var combined = document.createElement('div');
combined.innerHTML = content1 + " " + content2; // a little spacing
combined.id = 'new';

// 'container' can be whatever your containing element is
document.getElementById('container').appendChild(combined);

回答by Wesley Schleumer de Góes

Well, using jQuery you can do by this way:

好吧,使用 jQuery 你可以这样做:

$("body").append(
    $('<div/>')
        .attr("id","New")
        .html(
            $("#first).html() + $("#second").html()
        )
);

回答by Pandian

Try the below :

试试下面的:

Fiddle Example : http://jsfiddle.net/RYh7U/99/

小提琴示例:http: //jsfiddle.net/RYh7U/99/

If you already have a DIVwith ID "NEW" then try like below:

如果您已经有一个ID 为“NEW”的 DIV,请尝试如下操作:

$('#New').html($('#first').html() + " " + $('#second').html())

If you want to Create a divand then add the Content then try like below.

如果您想创建一个 div然后添加内容,请尝试如下。

$("body").append("<div id ='New'></div>")
$('#New').html($('#first').html() + " " + $('#second').html())

回答by youssDev

$("&lt;div&gt;&lt;/div&gt;").attr("id", "New").html($("#first").html() + $("#second").html()).appendTo($("body"));