0

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?

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174
  • 1
    That would be a neat trick. The problem, of course, is that CSS is cascading; you would have to parse the CSS yourself and figure out all of the modifications that the browser would apply to it. – Robert Harvey Aug 15 '12 at 22:22
  • 2
    no, because it's not a DOM object yet and the CSS files references DOM nodes. So these properties aren't set to the .super div, yet – kidwon Aug 15 '12 at 22:23

5 Answers5

3

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

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

Martin van Dam
  • 106
  • 1
  • 6
1

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.

Community
  • 1
  • 1
crash01
  • 117
  • 1
  • 8
1

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.

Michal
  • 13,439
  • 3
  • 35
  • 33
0

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.

Taylor
  • 373
  • 3
  • 13