Alisha Sharma
Alisha Sharma

Reputation: 149

Making object chain of element by adding parent name

I want to make chain that contain parent element and return me any attributes of top parent (class or id) by using there respective symbol (. and #). I have tried it but ran to infinity loop

html structure:-

<div id="main">
   <p>Hello Alisha..</p>
   <div class="container">
     <div id="toplayer">

     </div>
     <div class="mid_layer">
         <ul>
            <li>javascript</li>
            <li id="target">qbasic</li>
         </ul>
     </div>
  </div>
</div>

My js code:-

var t = document.getElementById("target");

 function  chain(el) {
    var f = {};
    var m = el;
    if (el !== null && el !== undefined) {
      var y = m.parentElement;
      while(null !== y){
        var r = {};
        r['parent'] = y;
        f[m.tagName] = r;
        var m = y;
      }
      return f;
     }
   }
  chain(t);

Loop dosn't stop in above program.

Please don't suggest me idea using jquery

Upvotes: 0

Views: 101

Answers (2)

Velimir Tchatchevsky
Velimir Tchatchevsky

Reputation: 2815

Move the assignment of y inside the loop (as DrC commented), as it is now y is always not null, hence the infinity loop.

var t = document.getElementById("target");

 function  chain(el) {
    var f = {};
    var m = el;
    if (el !== null && el !== undefined) {
      var y = m.parentElement;
      while(null !== y){
      y = m.parentElement;
        var r = {};
        r['parent'] = y;
        f[m.tagName] = r;
        var m = y;
      }
      return f;
     }
   }
  chain(t);

Upvotes: 1

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

If you only need to get the top parent element attribute, you dont need to create any chains. There are built in properties that collects that data anyway:

var t = document.getElementById("target");

console.log(t.offsetParent.children[0].id)

You can easily check available methods or properties in your Chromes console:

var t = document.getElementById("target");
dir(t)

Upvotes: 1

Related Questions