PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to loop over document.body in a function

 October 15, 2022     dom, javascript     No comments   

Issue

I have to write a version of getElementsByClassName but i'm having trouble using document.body in my function. It only returns null when called. I realize that the recursion part needs to be fixed and finished but first I'd like to know how to access document.body (along with its childNodes) and use it in a function. Or maybe I'm approaching it the wrong way?

var getElementsByClassName = function() {

  var bod = document.body;

  
  for (var i = 0; i < bod.childNodes.length; i++) {
    var thisNode = bod.childNodes[i];
    var classTest = bod.childNodes[i].className;
    if (classTest === classname) {
    }
    //recursion here
    if (thisNode.childNodes.length > 0) {
      getElementsByClassName();
    }
  }

};

Solution

Give the getElementsByClassName() function an argument of element and pass in each node that you want to recurse. Note that you can also use querySelectorAll() instead of writing your own.

var getElementsByClassName = function (element) {
  for (var i = 0; i < element.childNodes.length; i++) {
    var thisNode = element.childNodes[i];
    var classTest = thisNode.className;
    if (classTest === classname) {
    }
    //recursion here
    if (thisNode.childNodes.length > 0) {
      getElementsByClassName(thisNode);
    }
  }
};

getElementsByClassName(document.body);



Answered By - doublesharp
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing