Looking for the width and height of an html element using jquery closest to find it

StackOverflow https://stackoverflow.com/questions/16279106

  •  13-04-2022
  •  | 
  •  

سؤال

I'm trying to get the dimensions of an element via jquery and I'm not having much luck.

this is how I created my div.

var window = document.createElement( 'div' );
window.setAttribute( 'id', 'myWindow' + id );
window.setAttribute( 'data-minwidth', '75' );
window.setAttribute( 'data-minheight', '50' );
window.setAttribute( 'class', 'box_flat' + theme  + '  message' );
window.setAttribute( 'style', 'z-index:' + id );

var content = document.createElement( 'div' );
content.setAttribute( 'id', 'myContent' + id )
content.setAttribute( 'class', 'contents' )
window.appendChild( content );

document.body.appendChild( window )

This is how I'm trying to reach it.

var cont = $( element ).closest( ".content" ).find( 'div' )

element = window in this case.

I always get back an object that looks like a list of selectors. the .width() returns null as does the height. What is a better approach here?

هل كانت مفيدة؟

المحلول

Please don't redefine the window object here.. Use some other name for newly created div. Also, you don't need closest() in this case. Simple find() would be sufficient because your .content is child of window(which you shall change to something else)

نصائح أخرى

var cont = $( element ).find( ".content" );

closest is used to find the nearest ancestor matching the selector. "window" is not a descendant of .content it is a parent. You use find to find descendant element.

On a side note, you probably shouldn't use a variable named "window" as that already has a meaning in javascript.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top