[英]How can I list all the html tags from the string in js
I have one string which contain both texts and many html tags with there respective attribute and its value for example:- 我有一个字符串,其中包含文本和许多html标签,其中包含各自的属性及其值,例如: -
I am trying to takeout all the tag names and push inside array note:- I have two custom function named trim() and null() that removes all the spaces of string and checks whether supplied argument is null. 我试图取出所有的标签名称并推入内部数组注释: - 我有两个自定义函数,名为trim()和null(),它删除字符串的所有空格并检查提供的参数是否为空。
var a = ` <div class="box"> <span id="box-span"> <p class="texts">very long texts goes here.</p> <p class="texts">very long texts goes here</p> <p class="texts">very long texts goes here</p> </span> </div>`; var tags = function(string) { var array = ['hello']; var string = a.trim(''); var len = string.length; for (var i = 0; i < len; i++) { index1 = string.indexOf('>'); index2 = string.indexOf('<'); index3 = string.indexOf('/'); if (null(index1) && index1 !== -1 && null(index2) && index2 !== -1) { // if somthing is found x = string.substr(index1, index2); g = x.indexOf('/') // for end tag if (null(g) || g !== -1) { x = string.substr(index1, index2 - 1); array.push(x); } else { array.push(x); } z = string.substr(index2); // new string with reducing 1 tag if (z.length < len && z.length > 0) { tags(z) } else { return array; break; } } } } console.log(tags(a));
this is my idea but it dosn't works. 这是我的想法,但它不起作用。
Updated ; 更新 ; only fetch unique tags (no duplicates).
仅获取唯一标签(无重复)。
Something like will put you on the path to strip all availble tags
from HTML... 类似的东西会让你走上从HTML中剥离所有可用
tags
的道路......
var a = `<div class="box"> <span id="box-span"> <p class="texts">very long texts goes here.</p> <p class="texts">very long texts goes here</p> <p class="texts">very long texts goes here</p> </span> </div>`; var temp = document.createElement("div"); temp.innerHTML = a; var all = temp.getElementsByTagName("*"); var tags = []; for (var i = 0, max = all.length; i < max; i++) { var tagname = all[i].tagName; if (tags.indexOf(tagname) == -1) { tags.push(tagname); } } console.log(tags);
https://jsfiddle.net/9phzt1y2/2/ https://jsfiddle.net/9phzt1y2/2/
var str= `<div class="box"> <span id="box-span"> <p class="texts">very long texts goes here.</p> <p class="texts">very long texts goes here</p> <p class="texts">very long texts goes here</p> </span> </div>`; var tag = document.createElement("div"); tag.innerHTML = str; var t = tag.getElementsByTagName("*"); var ele = []; for (var i = 0; i < t.length; i++) { ele.push(t[i].tagName); } console.log(ele);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.