0

I try to insert into array all the classes

for example

   <div class="class1">

   <div class="class2">

   <div class="class3">

   <div id="class4">

   </div> 
   </div> 
   </div> 

   </div>

And javascript

      var a=document.getElementById("class4");
  var b=new Array(a.parentNode.className,a.parentNode.parentNode.className,
  a.parentNode.parentNode.parentNode.className);
  for(i=0;i<b.length;i++)
  {alert(b[i])}

This is work fine but my question is if I don't know how much parentNode there is to the class How can I loop all over the parentNode and insert it into the array?

6
  • I'm definitely not a web developer, but I'd perhaps a function that checks if a given element has a parent that is not document, then using a while loop with that function as the test? Commented Dec 20, 2012 at 6:24
  • But how can I get it without use parentNode.parentNode... Commented Dec 20, 2012 at 6:25
  • This is work fine? I doubt that. class4 is a class not an id so document.getElementById("class4"); wouldn't fetch the element. Commented Dec 20, 2012 at 6:25
  • Sorry I change it in my computer to check it and I forgot to change it here Commented Dec 20, 2012 at 6:27
  • Yes but I need the parents Commented Dec 20, 2012 at 6:37

2 Answers 2

1
​function allParents(node) {
    var arr = [];
    while (node) {
        arr.push(node);
        node = node.parentNode;
    }
    return arr;
}

console.log(allParents(document.getElementsByClassName("class4")[0]));
​
Sign up to request clarification or add additional context in comments.

1 Comment

Note that document.getElementById from OP's question won't work because "class4" is a class name, not an ID.
0

You can also use the .parents() jquery method http://api.jquery.com/parents/

1 Comment

the OP didn't mention about jquery

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.