-1

I want to reuse the certain class of CSS style of a webpage to the new Div element that I have added. I am using Greasemonkey to redesign the page.

How can I add bar1 style to myDiv?

Original div:

<div id="bar1" class="bar1">

New Div:

var myDiv = document.createElement('div');
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
kitokid
  • 3,009
  • 17
  • 65
  • 101
  • possible duplicate of [Javascript - How to add div class to createElement](http://stackoverflow.com/questions/1115310/javascript-how-to-add-div-class-to-createelement) – Brock Adams Jul 12 '12 at 03:17

3 Answers3

0
myDiv.className = 'bar1';

or

myDiv.className = document.getElementById ('bar1').className;
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • I can see myDiv class name is 'bar1' when I checked with firebug, but still the style is not applied to that myDiv. any idea? – kitokid Jul 12 '12 at 03:28
  • Some other CSS takes precedence then. Link to the page in question or post a pared-down page that demos the problem at http://pastebin.com/ or http://jsfiddle.net/ . – Brock Adams Jul 12 '12 at 03:34
0

Sounds like your end goal is really to make something like a bookmarklet. If you are just looking to add a class you can always just set the "className" on a object since the word 'class' is protected.

http://jsfiddle.net/scispear/tCzZM/

I also threw in something style sheet dynamically (but only for more modern browsers, older browsers require a bunch more work).

SciSpear
  • 2,008
  • 18
  • 18
  • This is a Greasemonkey question, so technically the only browser that matters is Firefox -- unless stated otherwise. (In which case it is more properly a "userscripts" question.) – Brock Adams Jul 12 '12 at 03:22
  • Bookmarklet was just speculation (you can also get greasemonkey working on chrome). My jsfiddle only showed how to add classes with and without jquery, it is browser agnostic... – SciSpear Jul 28 '12 at 01:29
0

Due to CSS inheritance, copying the class name is not enough, unless the new element is a sibling of the other. Even then, CSS3 selectors like nth-child may mess things up.

You should instead iterate over all relevant style properties and copy their computed values like so:

var stylesToCopy = ['color', 'background-color', ...];
var oldStyle = getComputedStyle(bar1);
for (var i = 0; i < stylesToCopy.length; i++) {
    myDiv.style[stylesToCopy[i]] = oldStyle[stylesToCopy[i]];
}
user123444555621
  • 148,182
  • 27
  • 114
  • 126