blue ghhgdtt
blue ghhgdtt

Reputation: 921

Is there other way to reference grandParent object in javascript

I have following code:

var objectParent:{
     child1:{
       test1:function(){},
       test2:function(){}
      },

      child2:{
       demo1:function(){},
       demo2:function(){},
       parent:this  // gives child2
       grandparent: .... // need to reference objectParent here

      }

    }

We can reference object by using this keyword, But what for grand object or i mean parent of parent object?

Now, i am using grandparent:objectParent to reference parent object

Is there other way like this selector to reference parentObject?

Are these my coding is bad,good or better?

Upvotes: 4

Views: 22829

Answers (4)

Abhishek Patel
Abhishek Patel

Reputation: 51

There's no need to go the long way doing div.parentNode.parentNode.parentNode. Instead you can just do div.offsetParent and you'll get the grandparent of the div.

Upvotes: 0

deadcoder0904
deadcoder0904

Reputation: 8683

I had to do div.parentElement.parentElement to achieve it.

One way to see what to access is by logging div.__proto__ to the console which shows you a long list of properties & methods you can call.

Upvotes: 2

Barmar
Barmar

Reputation: 781974

If all your objects have a parent property that refers to their parent, then can get the grandparent with object.parent.parent.

Upvotes: 10

jfriend00
jfriend00

Reputation: 707816

It's not real clear what you're trying to do.

If you have an element reference elem, then you can get its parent with elem.parentNode. You can get a parent's parent (e.g. a grandparent) with elem.parentNode.parentNode and so on.

If this isn't what you're trying to do, please explain in more detail what you mean by a grandparent object.


If you're not talking about DOM references at all and instead are asking about nested objects in plain javascript, then javascript does not contain any way to get the parent object that you are contained within. You would have to create a property on the child and set it if you need it that way after you've constructed the object (you can't set it with a static declaration either).

Upvotes: 3

Related Questions