2

I need the width of the parent div for calculations within the child div, but neither have been appended yet in the D3 chain. How can I extract the width out of e.g.

.element {
    width: 120px;
    height: 200px;
    box-shadow: 0px 0px 12px rgba(0,255,255,0.5);
    border: 1px solid rgba(127,255,255,0.25);
    text-align: center;
    cursor: default;
}
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Mic C
  • 501
  • 2
  • 7
  • 18

1 Answers1

3

You can use getComputedStyle and a temporary DOM element with the class name to read the applied CSS.

var el = document.createElement("div");
el.className = "element";
document.body.appendChild(el);
var elementWidth = getComputedStyle(el, null).width;
document.body.removeChild(el);

This code will create a new div element with the class of element, add it to the body, read the applied CSS width setting it to the variable elementWidth, and remove the temporary element from the DOM.

Alternatively, you can do this with jQuery.

var el = $("div").addClass("element").appendTo("body");
var elementWidth = el.css("width");
el.remove();
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • Is there a reason you chose not to use d3 for the DOM manipulation? – Mike Precup Aug 08 '14 at 00:43
  • 1
    @MikePrecup D3 isn't very helpful for single element manipulation like this. Vanila JS is faster. – Alexander O'Mara Aug 08 '14 at 00:48
  • The outer element and inner div with its d3 svg are placed within a THREE.CSS3DObject object to be rendered in a Three.js canvas with a THREE.CSS3DRenderer() ... so I'm thinking that the element actually gets a width about 10 miles down the pike from where I need it for the x attr of a rect within the svg. Should have mentioned that. Creating and destroying works perfectly - thanks for that ..... did more googling on reading css class with js - nasty stuff! – Mic C Aug 08 '14 at 08:23
  • looking at Mike's comment .... at the moment I am doing a lot of create elements before the d3 statement to add svg data. Is Mike saying that I could do all of this within a d3.select("body) .... statement and that the parent is passed on to each .append('child') so that all parent attributes including width are available to each child as it is created? – Mic C Aug 10 '14 at 21:41
  • @MicC I think Mike was asking why I didn't use D3 to add the temporary element and suggesting that you could calculate the width of the parent element before appending the child. – Alexander O'Mara Aug 10 '14 at 22:02