i am trying not to repeat the selector and get to its children via a the same objects parentElment declared variable.
I tried:
testimonialsBelt={
parentElment:$(".testimonialsCntnr ul"),
childrenElem:this.parentElment.children().length
}
I also tried:
testimonialsBelt={
parentElment:$(".testimonialsCntnr ul"),
childrenElem:$("testimonialsBelt.parentElment").children().length
}
but i keep on getting a undefined when calling alert(testimonialsBelt.childrenElem).
- is there anyway to get the jquery object with object literals?
- What is the rule? when can i use
thisand when must i have the full path? (in this casetestimonialsBelt.parentElment).
i am trying to have all these variables in one object called testimonialsBelt. i know i can do this with loose javaScript.
Thanks
In object literals, you can only use
thisto refer to the object that you’re declaring inside of a function. Try the following:The difference in calling childrenElem is that instead of using
alert(testimonialsBelt.childrenElem), you would instead havealert(testimonialsBelt.childrenElem()).Otherwise,
thisrefers to the current scope that you are in (typically window if you are declaring the object literal as a global).Addressing your edit: I’m not sure what you mean by “loose javascript,” but I assume you mean as simple as possible. In which case, you can try the following, although I’m not a big fan of the method. It’s more verbose, but is easy to understand.
This gives you an object where
childrenElemis static (it doesn’t change) and avoids calling$(".testimonialsCntnr ul")twice. However, if you expect$(".testimonialsCntnr ul").children()to change, then you will need to use my first example.