Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Read a CSS property of a not-yet added to the DOM div

If I am theoretically obtaining the following HTML from an ajax call:

<div class="super">
    <span> Some Content </span>
</div>

and wrapping it in a jquery object $data, the div becomes available to me for operations, but it is not yet added to the DOM, until I insert it with some manipulation function call.

In the linked css file I have the width and height settings for super css class.

Is there a way for me to read what the width and height for the element will be when it is added?

Upvotes: 0

Views: 2818

Answers (5)

Michal
Michal

Reputation: 13639

Well there are a couple of ways you could do this. If you want to read the stylesheet value you need to go through document.styleSheets objects and find your selector there for one stylesheet with one property the code would look like this (you would probably need to write code to search for a class name in the object that gets returned):

<style>
        .super {
            height: 200px;
        }

    </style>
<script>
document.styleSheets[0].cssRules[0].style.height
</script>

Alternatively simply add the element to the DOM somewhere off screen(like in a container that has a top margin set to -9000px) /or as an empty element and get the height of added element using jquery height() or css() methods.

Upvotes: 1

Taylor
Taylor

Reputation: 393

What I've done is create the div in a

<div id="sandbox" style="display:none;">

</div>

So that I can reference it in the DOM without it being visible. And once I'm done manipulating it there, move it to wherever I want.

Upvotes: 0

adeneo
adeneo

Reputation: 318182

Just create a fake element with the same class, insert it into the DOM, get the style and remove the element:

var elem = $("<div class='super'></div>"),
    width = elem.appendTo('body').css('width');
    elem.remove();

FIDDLE

Upvotes: 3

crash01
crash01

Reputation: 117

Best way to do this is create the hidden element with "super" class and then use:

var width = $('.super').css('width');
var height = $('.super').css('height');

So, you can do something like this:

var $element = $('<div class="super"><span></span></div>').hide().appendTo("body");
var width = $element.css('width');
var height = $element.css('height');
$element.remove();

There is familiar thread: Get a CSS value from external style sheet with Javascript/jQuery.

Upvotes: 1

Martin van Dam
Martin van Dam

Reputation: 106

No, not with jquery, because you can only get attributes from the div AFTER it is inserted in the DOM.

Upvotes: 1

Related Questions