Get path of object and convert it to string in JavaScript -


how generate string of object's path? example, want turn following path (not contents) string:

object = grandparent.children[2].children[4].whatever; 

i need function this:

function stringifypath(obj) {     // somehow return "grandparent.children[2].children[4].whatever"; } 

you can't in javascript unless each object stores reference it's own parent , there's known way navigate children (like dom nodes do).

this because when have object embedded in object (your parent/child relationship speak of), isn't object embedded in another. child independent object , there's reference in parent. same child stored in many different places. javascript's point of view, doesn't have parent. it's object many different things may have reference to.

if each child object stored reference own parent , there known way walk children @ level, possible write code construct path you've said, you'd have lot more specific these objects , how find out child index given object is.

for example, if these dom objects meets both of criteria (child contains reference parent , there's known way navigate children of given object) , wanted root parent document.body, this:

function getsiblingposition(obj) {     var siblings = obj.parentnode.children;     var elemcnt = 0;     (var = 0; < siblings.length; i++){           if (siblings[i] === obj) {             return elemcnt;         } else {             if (siblings[i].nodetype === 1) {                 ++elemcnt;             }         }     } }  function getpath(obj) {     var path = "";     while (obj && obj !== document.body) {         var cnt = getsiblingposition(obj);         path = ".children[" + cnt + "]" + path;         obj = obj.parentnode;     }     path = "document.body" + path;     return path; } 

working demo: https://jsfiddle.net/jfriend00/8w9v8kpf/


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -