Clone html elements

0

How can I clone html elements and be able to change their properties independently?

I tried this:

function clonar(){
  var c = document.getElementById("about0");
  var clon = c.cloneNode(true);
  clon.style.width = "1000px";
  document.body.appendChild(clon);
}
#about {
  width: 350px;
  height: 350px;
  border-radius: 175px;
  background-color:gray;
  
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="about"></div>
</body>
</html>

With "independent" I mean that the cloned elements can change their properties, I mean all the properties inherited, if I want to change the color, etc.

    
asked by Eduardo Sebastian 10.09.2017 в 19:26
source

2 answers

0

You are not invoking the function clonar() and the id about0 does not exist, it should be about

function clonar() {
  var c = document.getElementById("about");
  var clon = c.cloneNode("about");
  clon.style.width = "50px";
  clon.style.height = "50px";
  document.body.appendChild(clon);

 
}
clonar();
#about {
  width: 350px;
  height: 350px;
  border-radius: 175px;
  background-color: gray;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div id="about"></div>
</body>

</html>
    
answered by 10.09.2017 / 19:43
source
2

According to the documentation you can use Node # cloneNode :

  

The Node.cloneNode () method returns a duplicate of the node on which   This method was called.

And clearly you are using what I understand that the error you have is that you are not calling the clone function and you are using the wrong id, instead of about0 , it should be about . Here your edited example

function clonar(){
  var c = document.getElementById("about");
  var clon = c.cloneNode(true);
  clon.style.width = "1000px";
  document.body.appendChild(clon);
  
}
#about {
  width: 350px;
  height: 350px;
  border-radius: 175px;
  background-color:gray;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="about" onclick="clonar()"></div>
</body>
</html>
    
answered by 10.09.2017 в 19:34