Duplicating an Element (And Its Style) with JavaScript

How to clone Style element with its cssRules?

Cloned node doesn't get its own sheet property (or CSSStyleSheet object) until it is added to be part of the document <head> or <body>

We can give styleClone variable it's own sheet by inserting it to the head like the code is doing for style variable!

Here's what I got

// Add style a tag to head
var style = document.createElement("style");
style.id = "style",
style.type = "text/css",
document.head.appendChild(style);

// Insert some stylesheet rules
var sheet = style.sheet;
sheet.insertRule("p {background-color: red}", sheet.cssRules.length);
sheet.insertRule("p {color: white}", sheet.cssRules.length);
console.log(style.sheet); //Display an object with Css rules

// Try to clone
var styleClone = style.cloneNode(true);
console.log(styleClone.sheet); //Display null !

// Added
document.head.appendChild(styleClone);
// Copy all rules from style variable
for (var i = 0; i < style.sheet.rules.length; i++) {
styleClone.sheet.insertRule(style.sheet.rules[i].cssText)
}

How do I clone an HTML element's style object using JavaScript or jQuery?

var curr_style;
if (window.getComputedStyle) {
curr_style = window.getComputedStyle(el);
} else if (el.currentStyle) {
curr_style = $.extend(true, {}, el.currentStyle);
} else {
throw "shit browser";
}

style has non-enumerable properties which makes .extend fall over. You want to use the getComputedStyle method to get the styles of an element.

You also want to support older versions of IE by extending el.currentStyle which does have enumerable properties.

The first argument (when set to true) tells jQuery to do a deep clone.

Copying an Element and Changing a Class in pure Javascript

Six lines of code using:

  • .querySelector()........: Reference

  • .cloneNode()................: Replicate

  • .classList/className: Rename

  • .appendChild().............: Relocate

Details commented in Snippet


SNIPPET

// Reference the .footer-menuvar ftMenu = document.querySelector('.footer-menu');
// Reference the .page-navvar pgNav = document.querySelector('.page-nav');
// Clone the .footer-menuvar dupe = ftMenu.cloneNode(true);
// Clear .footer-menu of any classesdupe.className = "";
// Add .main-menu to .footer-menu's clonedupe.classList.add('main-menu');
// Append the clone of .footer-menu to .page-navpgNav.appendChild(dupe);
.main-menu {  border: 2px solid white;  background: red;  color: white;  width: 250px;}
.footer-menu { border: 1px solid black; background: tomato; width: 250px;}
footer,header { border: 2px dashed blue;}
footer { background: seagreen}
header { background: goldenrod;}
main { background: brown; color: white}
.social { background: lightblue; border: 2px solid grey; width: 250px;}
<header>  HEADER  <nav class="page-nav">    <ul class="social">      <li>FB</li>      <li>TW</li>    </ul>  </nav></header><main>  MAIN CONTENT</main><footer>  FOOTER  <nav class="footer">    <ul class="footer-menu">      <li>SO</li>      <li>MDN</li>      <li>DT</li>    </ul>  </nav></footer>

change css of cloned element

I believe remove the class and add a new class after cloning would solve your problem.

source.clone(true).removeClass('oldDivChild').addClass('myNewClassName').appendTo('.popoverContent')

Alternatively, You could also make the children css rule only apply to the parent > target pair without changing your javascript

.oldDiv .oldDivChild {
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 70%;
background-color: blue;
}

that way the cloned div would have the .oldDivChild, but the css won't get applied because it's on a different parent.

How can I programmatically copy all of the style attributes from one DOM element to another

Have you tried cloneNode? It can copy the element and all of its children in one fell swoop.
http://www.w3schools.com/dom/met_element_clonenode.asp

javascript copy element to clipboard with all styles

You can try the following fiddle. It works with every text style there is and it's interoperable with MS Word and Pages (I just tested it).

The code is pretty straightforward so I wouldn't really get into the depths of it, but feel free to drop me any questions should you feel like. :)

const copyWithStyle = ( element ) => {

const doc = document;
const text = doc.getElementById( element );
let range;
let selection;

if( doc.body.createTextRange ) {

range = doc.body.createTextRange();
range.moveToElement( text );
range.select();

} else if ( window.getSelection ) {

selection = window.getSelection();

range = doc.createRange();
range.selectNodeContents( text );

selection.removeAllRanges();
selection.addRange( range );

}

document.execCommand( 'copy' );
window.getSelection().removeAllRanges();
document.getElementById( 'clickMe' ).value = 'Copied to clipboard!';

}

https://jsfiddle.net/aypdg3kL/

From the example in JSFiddle

HTML

<div id="text" style="color:red">
<i>Hello</i> world!
</div>
<input id="btn" onclick="CopyToClipboard('text')" type="button" value="Copy" />

JS

function CopyToClipboard(element) {

var doc = document
, text = doc.getElementById(element)
, range, selection;

if (doc.body.createTextRange)
{
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
}

else if (window.getSelection)
{
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById("btn").value="Copied";
}


Related Topics



Leave a reply



Submit