Javascript display width jquery

How can I get the width and height of a div element with jquery?

Give the div an id, and use that instead of the id of your image.

There are 3 potential methods of doing this:

One:

$("#preview").parent().css('width'); $("#preview").parent().css('height'); 

Two:

$("#preview").parent().width(); $("#preview").parent().height(); 

This will not include margins, padding and border.

Three:

$("#preview").parent().outerWidth(); $("#preview").parent().outerHeight(); 

This will include the padding, border, and optionally margin. To include margin you must add true in the function, i.e. .outerHeight(true) .

You’re using $(«#preview») which will return the img since the img tag is the one with id=»preview»

First option:

Second, better option:

Give the div an id, say «foofoo»:

To make it into an integer wrap in parseInt() :

var previewwidth = $("#preview").parent().width(); var previewheight = $("#preview").parent().height(); 

You can use height() and width() . Look at the API for these sorts of questions..

Also, as pointed out above, your selector isn’t correct.

You can do this simply like that (jsfiddle as an example):

var mydiv = jQuery('#preview').parent('div'); var mywidth = mydiv.width(); var myheight = mydiv.height(); 

preview is the ID of your image so of course your code is returning the size of the image. Just give your div a different unique ID, and use that instead of #preview in your jQuery selector.

 
daisy_03_20110712163828_extra.jpg

The following will return the width/height of the div as «100px»:

var previewwidth = $("#myDiv").css('width'); var previewheight = $("#myDiv").css('height'); 

And to get the result as a unit-less number instead of a string:

var previewwidth = $("#myDiv").width(); var previewheight = $("#myDiv").height(); 

Источник

set element width or height using jquery

Lets say I want to assign element’s width to itself. For example, I have a div with content and I want to assign style=»width. » it.
Then in jQuery I do:

Which looks for me totally wrong since it looks like how can I set the width by getting it.. Is there any better way to do it?

For me it looks fine, since getting and setting is done differently in jQuery. While getting the width is mostly calculated, when setting — it is set explicitly with styles.

when you’re not passing a parameter to set the width, what’s left but to just return the width that’s already set?

5 Answers 5

document.getElementById('divName').style.width = '10px'; 

I am not asking how to do something. I am asking if this is the right way and whether this is wrong or not.

This has 2 changes, it now uses .width() and .height(), as well as runs the code on the document.ready event.

Without the $(function() < >) wrapper (or $(document).ready(function() < >) if you prefer), your element may not be present yet, so $(«#mainTable») just wouldn’t find anything to. well, do stuff to.

Better to add CSS using JQuery following way :

I am not asking how to do something. I am asking if this is the right way and whether this is wrong or not.

If you prefer the style, you could use jQuery’s .css() method:

$('.element').css('width', $('.element').width()); 

If you have multiple elements with the same class (but different widths) you can do this:

$('.yourClass').width( function(id, width) < return width; >); 

I am not asking how to do something. I am asking if this is the right way and whether this is wrong or not.

You asked for a better way, since there are lots of answers/comments here telling you that it isn’t wrong what you’re currently doing I just gave you another example covering a case you might not have considered yet, e.g. setting style=»width. » of multiple, different sized elements with the same selector.

Источник

.width()

Get the current computed width for the first element in the set of matched elements or set the width of every matched element.

Contents:

.width() Returns: Number

Description: Get the current computed width for the first element in the set of matched elements.

version added: 1.0 .width()

The difference between .css( «width» ) and .width() is that the latter returns a unit-less pixel value (for example, 400 ) while the former returns a value with units intact (for example, 400px ). The .width() method is recommended when an element’s width needs to be used in a mathematical calculation.

This method is also able to find the width of the window and document.

// Returns width of browser viewport
$( window ).width();
// Returns width of HTML document
$( document ).width();

Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box . To avoid this penalty, use .css( «width» ) rather than .width() .

Note: Although style and script tags will report a value for .width() or height() when absolutely positioned and given display:block , it is strongly discouraged to call those methods on these tags. In addition to being a bad practice, the results may also prove unreliable.

Additional Notes:

  • The number returned by dimensions-related APIs, including .width() , may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.
  • The value reported by .width() is not guaranteed to be accurate when the element or its parent is hidden. To get an accurate value, ensure the element is visible before using .width() . jQuery will attempt to temporarily show and then re-hide an element in order to measure its dimensions, but this is unreliable and (even when accurate) can significantly impact page performance. This show-and-rehide measurement feature may be removed in a future version of jQuery.

Example:

Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.

html>
html lang="en">
head>
meta charset="utf-8">
title>width demo title>
style>
body
background: yellow;
>
button
font-size: 12px;
margin: 2px;
>
p
width: 150px;
border: 1px red solid;
>
div
color: red;
font-weight: bold;
>
style>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
button id="getp">Get Paragraph Width button>
button id="getd">Get Document Width button>
button id="getw">Get Window Width button>
div>  div>
p>
Sample paragraph to test width
p>
script>
function showWidth( ele, w )
$( "div" ).text( "The width for the " + ele + " is " + w + "px." );
>
$( "#getp" ).on( "click", function( )
showWidth( "paragraph", $( "p" ).width() );
> );
$( "#getd" ).on( "click", function( )
showWidth( "document", $( document ).width() );
> );
$("#getw").on( "click", function( )
showWidth( "window", $( window ).width() );
> );
script>
body>
html>

Demo:

.width( value ) Returns: jQuery

Description: Set the CSS width of each element in the set of matched elements.

version added: 1.0 .width( value )

An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).

version added: 1.4.1 .width( function )

A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set.

When calling .width("value") , the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the width (such as 100px , 50% , or auto ). Note that in modern browsers, the CSS width property does not include padding, border, or margin, unless the box-sizing CSS property is used.

If no explicit unit is specified (like "em" or "%") then "px" is assumed.

Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property.

Example:

Change the width of each div the first time it is clicked (and change its color).

Источник

What is the Javascript equivalent for jQuery's width() function?

I want to be able to calculate the width, in pixels, of an element that has the width css property set to 'auto' . I have tried element.style.width but didn't work because it returned 'auto' . I notices that the jQuery function width() returns the length in px, but I cannot use jQuery to solve this, because it is not available in my page. So, does anybody know an equivalent method for jQuery width() ? Thanks.

The getWH() function in the jQuery source will reveal the implementation. (Called with name = "width" .)

3 Answers 3

element.getBoundingClientRect().width 

internally, it has some other stuff on top to deal with browser differences.

It returns an elements rendered size, where as .offsetxx returns sizes according to the box model.

element.getBoundingClientRect() 

Is the most accurate way to get an elements "real" dimensions.

Here is a post by John Resig ( author of jQuery ) on the matter.

Actually, very often $el.width() and $el.outerWidth() gives me zero, while el.getBoundingClientRect().width gives me the correct value, on both latest Firefox and Chrome, using jQuery 2.1.4

Wasted 2 hours on this.
For my case other answers did not work so combining others answers & my findings into one post with examples, for easy reading:

For an element like select , the width() in JQuery is same as clientWidth in JavaScript.

Sample code below, including output:

// Add jQuery library in HTML: // //  // let eleId = 'myselectid1'; // NOTE: Provide your element id below // jQuery console.log( $('#' + eleId).width() ); // JavaScript let ele = document.getElementById(eleId); console.log(ele.clientWidth); // 58 // includes padding into calculation console.log(ele.offsetWidth); // 60 // includes border size and padding into width calculation console.log(ele.getBoundingClientRect().width); // 60 // includes border size and padding into width calculation console.log(window.getComputedStyle(ele, null).getPropertyValue("width")); // 60px (note the px in value, you may also get values like 'auto') // all dynamic values for all CSS properties, IE>=9 console.log(ele.style.height); // empty string // if you set it earlier, you would get this console.log(ele.innerWidth); // undefined // only works on window object, not on element like select/ div - fails in older IE 

Источник

Читайте также:  Javascript popup height and width
Оцените статью