Javascript скопировать элемент html

Node: cloneNode() method

The cloneNode() method of the Node interface returns a duplicate of the node on which this method was called. Its parameter controls if the subtree contained in a node is also cloned or not.

Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.onclick = someFunction ). Additionally, for a element, the painted image is not copied.

Warning: cloneNode() may lead to duplicate element IDs in a document!

If the original node has an id attribute, and the clone will be placed in the same document, then you should modify the clone’s ID to be unique.

Also, name attributes may need to be modified, depending on whether duplicate names are expected.

Читайте также:  Php script for windows

To clone a node to insert into a different document, use Document.importNode() instead.

Syntax

Parameters

If true , then the node and its whole subtree, including text that may be in child Text nodes, is also copied.

If false , only the node will be cloned. The subtree, including any text that the node contains, is not cloned.

Note that deep has no effect on void elements, such as the and elements.

Return value

The new Node cloned. The cloned node has no parent and is not part of the document, until it is added to another node that is part of the document, using Node.appendChild() or a similar method.

Example

let p = document.getElementById("para1"); let p_prime = p.cloneNode(true); 

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

HTML DOM Element cloneNode()

The cloneNode() method creates a copy of a node, and returns the clone.

The cloneNode() method clones all attributes and their values.

Set the deep parameter to true if you also want to clone descendants (children).

Insert Back

To insert a cloned node back into the document, use:

See Also:

Syntax

Parameters

Parameter Description
deep Optional.
false — Default. Clone only the node and its attributes.
true — Clone the node, its attributes, and its descendants.

Return Value

More Examples

Example

Copy the «demo» element, including attributes and child elements, and append it to the document:

const node = document.getElementById(«demo»);
const clone = node.cloneNode(true);
document.body.appendChild(clone);

Browser Support

element.cloneNode() is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

4 Ways To Duplicate HTML Elements In Javascript (Simple Examples)

Welcome to a tutorial on how to duplicate HTML elements. So you are working on a project that requires the creation of evil clones, probably to ease tasks like creating table rows and list items?

An easy way to duplicate an HTML element in Javascript is to use the cloneNode() function:

  • var original = document.getElementById(«ID»);
  • var clone = original.cloneNode(true);
  • clone.removeAttribute(«id»);
  • document.getElementById(«ID»).appendChild(clone);

But there are more mechanisms in Javascript that we can use to clone elements. Just how exactly does each one work? Let us walk through some examples – Read on to find out!

TLDR – QUICK TUTORIAL

Duplicate HTML Elements In Javascript

TABLE OF CONTENTS

JAVASCRIPT DUPLICATE HTML ELEMENTS

All right, let us now get into the various ways of cloning HTML elements in Javascript.

METHOD 1) CLONE NODE

 
TITLE

TEXT

  • Grab the source element – var s = document.getElementById(«source»)
  • Create an evil clone – let clone = s.cloneNode(true) .
    • Take note of the true parameter here, this is to specify “also clone the children enclosed within”. By default, this is false and the children will be excluded from the cloning vat.
    • Do be extra careful, the clone will also share the same id . Remember to remove or replace the id for the clone.

    METHOD 2) INNER HTML

     
    TITLE

    TEXT

    • Get the source and destination elements – document.getElementById(«source») , document.getElementById(«destination») .
    • Simply copy the HTML from the source to the destination – d.innerHTML = s.innerHTML .

    That’s all, but take note that innerHTML will only include the “internal HTML”, exclusive of the tag itself. I.E. s.innerHTML is exclusive of itself.

    METHOD 3) OUTER HTML

     
    TITLE

    TEXT

    Yep… This should be Captain Obvious now – outerHTML also includes the element itself.

    METHOD 4) CLONING FROM A TEMPLATE

        
    // (C1) GET SOURCE + DESTINATION var s = document.getElementById("source"), d = document.getElementById("destination"); // (C2) APPEND ROWS BY CLONING THE TEMPLATE for (let i=1; i

    This is probably one that not many people know about. Yes, there is a legit HTML tag, and it comes in very handy in appending things like table rows plus list items. But please take note that handling the tag is slightly different. We are using importNode() here to handle the cloning instead of the “usual” cloneNode() .

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

    WHICH IS THE BETTER METHOD?

    Well, it really depends on the situation. Personally, I am pretty much stuck to using innerHTML as a beginner, thinking that it is convenient and easy to understand without all that object-oriented madness.

    It was only later that I realized the line of thought is very wrong. As demonstrated above, the “object-oriented way” of cloning a template can be very handy in appending new rows and items quickly; Using innerHTML would have been a mess otherwise, having to manually type out all the HTML code as a string.

    INFOGRAPHIC CHEAT SHEET

    THE END

    Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    Источник

    Как на чистом js копировать html элемент со всеми его дочерними элементами?

    Делаю галерею работ. Мне надо чтобы при клике на кнопку «ещё больше» появлялся ещё один блок с работами. Создать eventListener я смог а вот как скопировать галерею я не понял пожалуйста помогите. Вот код:
    https://codepen.io/air_man6/full/QWLodrq

    airman66

    airman66

    erge

    такое мне кажется все делают по разному, что правильно выбираете сами.
    варианты:
    1. блок с работами имеет фиксированную высоту с overflow: hidden
    при нажатии на кнопку высота блока увеличивается, блок с кнопкой скрывается.
    можно это дело анимировать, ну чтоб плавно высота увеличивалась.
    2. блок с работами состоит из нескольких блоков, по умолчанию показывается первый, при нажатии на кнопку появляется второй блок (меняем ему display), блок с кнопкой скрывается.
    3. добавлять элементы скриптом, через .appendChild(childElement) например:

    document.querySelector(".works__more__btn").addEventListener("click", function() < var elem = document.createElement("div"); elem.setAttribute("class", "works__content__smallRow"); elem.innerHTML = `    `; document.querySelector(".works__content").appendChild(elem); document.querySelector(".works__more").style.display = "none"; >);

    UPD:
    собственно копирование:

    вы правильно сделали cloneNode, но.
    см. Метод Node.cloneNode()
    если вы хотите копировать с дочерними элементами, то необходимо передать параметр «deep» = true

    document.querySelector(".works__more__btn").addEventListener("click", function() < document.querySelector(".works__content").appendChild(document.querySelector(".works__content").cloneNode(true)); document.querySelector(".works__more").style.display = "none"; >);

    Источник

Оцените статью