-2

I'm attempting to walk the DOM of a page using javascript, and do a simple alert on every tag, to display the tagName attribute. It doesn't seem to be working.

This is the code and the HTML in a jsfiddle (and beow) https://jsfiddle.net/fluffymuffins/fw208ozk/

I don't see any alerts. What's wrong?

HTML

<body>
test text
<p>
some paragraph
</p>
<img src="http://example.com/image.jpg">
</body>

JS

var results = [];

walkDOM(document.body, function(node) {
    alert(node.tagName);
});

var walkDOM = function (node,func) {
        func(node);                     //What does this do?
        node = node.firstChild;
        while(node) {
            walkDOM(node,func);
            node = node.nextSibling;
        }

    };
hichris123
  • 10,145
  • 15
  • 56
  • 70
Daisetsu
  • 4,846
  • 11
  • 50
  • 70
  • There is an awesome tool which may help you — [posthtml](https://github.com/posthtml/posthtml). It's like a PostCSS, but for HTML. It has almost the same API, so there is nothing hard to make you own simple plugin that will do exactly what you need. – denysdovhan Apr 10 '16 at 20:29
  • Why would people downvote this without even explaining why. – Daisetsu Apr 10 '16 at 20:49

1 Answers1

2

So, you are calling a method that doesn't exists yet:

Easily call after your method declaration:

var results = [];

//declaration before
var walkDOM = function (node,func) {
        func(node);                     //What does this do?
        node = node.firstChild;
        while(node) {
            walkDOM(node,func);
            node = node.nextSibling;
        }
};    

//invoke method after
walkDOM(document.body, function(node) {
    alert(node.tagName);
});

Your updated Fiddle: https://jsfiddle.net/diegopolido/fw208ozk/3/

The func(node); line means that you are invoking the function from the args, maybe this example will clarify your mind:

var walkDOM = function (node,func) {
        func(node);  //this will invoke the functionToInvoke from arg
        node = node.firstChild;
        while(node) {
            walkDOM(node,func);
            node = node.nextSibling;
        }
};    

var functionToInvoke = function(node) {
    alert(node.tagName);
};

walkDOM(document.body, functionToInvoke);

Your updated Fiddle for that: https://jsfiddle.net/diegopolido/fw208ozk/5/

Diego Polido Santana
  • 1,425
  • 11
  • 19
  • Thanks, I haven't written JS in years. I forgot that the order of definition matters. – Daisetsu Apr 10 '16 at 20:53
  • @Daisetsu Your's was a function expression like `var funcName = function(){}` and due to the JS hoisting rules they must be declared before they are called however if you had done like `function funcName(){}` then it would be a function definition and you could have placed it anywhere and call from anywhere (provided calling within an accessible scope of course) – Redu Apr 10 '16 at 22:26