Naor
Naor

Reputation: 24103

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:

elem.width(elem.width());

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?

Upvotes: 0

Views: 4873

Answers (5)

Seimen
Seimen

Reputation: 7250

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

$('.yourClass').width( function(id, width) {
    return width;
});

See the docs for explanation.

Upvotes: 0

Aarif Qureshi
Aarif Qureshi

Reputation: 474

try this

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

Upvotes: 1

tmaximini
tmaximini

Reputation: 8503

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

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

Upvotes: 0

Shivaji Ranaware
Shivaji Ranaware

Reputation: 169

Better to add CSS using JQuery following way :

$(function() { $("#test").css({ width : '30px', height : '30px' }); });

Upvotes: 0

Prashant Gorvadia
Prashant Gorvadia

Reputation: 23

You can do this

$(function() {
  $("#mainTable").width(100).height(200);
});

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.

Upvotes: 0

Related Questions