/    Sign up×
Community /Pin to ProfileBookmark

Get “width” value from “style” from
element?

Assume I have (simplified) a code like:

`<div class=”foobar” style=”width: 632px; margin-right:0px “>`

Now I want to get resp retrieve with javascript/jQuery the width of this element;

Keep in mind that the width value shown above could vary depending on occurency.

I miss a jQuery function like

`$(“.foobar”).getwidth();`

resp. (more advanced to use in a comprehensive command).

`$(“.foobar”).width($(“.foobar”).getwidth() + 120px);`

How can I achieve this?

to post a comment
CSS

5 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumDec 13.2021 — @pstein#1640490 You can access the styles of an element directly:

`const width = document.querySelector('.foobar').style.width;</C><br/>
and modify it:
<CODE>
`<i>
</i>const newWidth = parseInt(width) + 120 + 'px';
document.querySelector('.foobar').style.width = newWidth;<i>
</i>
``
Copy linkTweet thisAlerts:
@psteinauthorDec 15.2021 — This looks good. However it assigns the new width only to the first found/matched element.

How can I perform the calculation and assignment for ALL elements which match the class?

``<i>
</i> document.querySelectorAll(".foobar").forEach(
const width = style.width;
const newWidth = parseInt(width) + 120 + 'px';
style.width = newWidth;
);<i>
</i>
``



does not work;
Copy linkTweet thisAlerts:
@SempervivumDec 15.2021 — `forEach</C> is a good approach, however you didnt't specify the parameter. Try it like this:
<CODE>
`<i>
</i>document.querySelectorAll(".foobar").forEach(function(item) {
// item is the element currently being processed
const width = item.style.width;
const newWidth = parseInt(width) + 120 + 'px';
item.style.width = newWidth;
});<i>
</i>
``
Copy linkTweet thisAlerts:
@psteinauthorDec 16.2021 — works :-)

Thank you
Copy linkTweet thisAlerts:
@digitalpakistaniDec 16.2021 — [Digital Pakistan](https://) accommodates the best Telenor call packages services details. Daily, weekly and monthly. Telenor connects you with your loved one.

https://digitalpakistani.pk/category/internet/
×

Success!

Help @pstein spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.9,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...