Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain width from CSS class before element appended?

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;
}
like image 855
Mic C Avatar asked May 26 '26 17:05

Mic C


1 Answers

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();
like image 90
Alexander O'Mara Avatar answered May 28 '26 06:05

Alexander O'Mara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!