2

I am just getting into jQuery so please forgive this maby stupid question, but I encountert the following:

$('#pb_inner').css('width',data + '%');

this code works fine. However I wonder why I can't do the following?

$('#pb_inner').style.width=data + '%';

4 Answers 4

3

Because $('#pb_inner') returns an array like jQuery object. A collection, not a single object (and even then, it would be another jQuery object):

From the docs:

(...), jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements.


You would have to use get:

$('#pb_inner').get(0).style.width=data + '%';

The .get() method grants us access to the DOM nodes underlying each jQuery object

Sign up to request clarification or add additional context in comments.

Comments

1

Because $('#pb_inner') returns a jQuery object not the raw DOMElement. You could use the properties if you retrieve the actual DOMElement from that jQuery object, for example:

$('#pb_inner').get(0).style.width=data + '%';

Comments

1

the selector $('#pb_inner') returns an array of jQuery wrapped objects matching the given parameter string.

the following will work

$('#pb_inner').get(0).style.width=data + '%'

get(0) will return the first object from the jQuery array, as a native DOM element.

Comments

1

And btw there is an advantage with using jQuery .css() method since you can write multiple CSS rules in it by passing an object, like in example:

$('#pb_inner').css({
  'width': data + '%',
  'height': data + '%',
  'color': '#eaeaea'
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.