The content of this article is to introduce the method of using js to obtain all tags on the page (detailed code explanation). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I saw a question two days ago, asking how to get all the tags from the page and check their number. It seems a bit interesting, so I’ll give it a try
Let's first think about it. We need to get tags from the page. Needless to say, we will definitely think of DOM operations. After getting it, we are not sure whether a certain element has sub-elements. So what should we do? At this time we I will definitely think of recursion
Now that we have DOM operations and recursion, it is easier to handle, and we can write code directly. The following is the code with comments, you can pull it down for reference
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <ul></ul> </body> </html> <script> var map = {}; //采用递归调用的方法,比较方便和简单。 function fds(node) { if (node.nodeType === 1) { //这里我们用nodeName属性,直接获取节点的节点名称 var tagName = node.nodeName; //判断对象中存在不存在同类的节点,若存在则添加,不存在则添加并赋值为1 map[tagName] = map[tagName] ? map[tagName] + 1 : 1; } //获取该元素节点的所有子节点 var children = node.childNodes; for (var i = 0; i < children.length; i++) { //递归调用 fds(children[i]) } } fds(document); console.log(map) </script>
The above is the detailed content of How to get all tags on the page using js (detailed code explanation). For more information, please follow other related articles on the PHP Chinese website!