我有一个字符串,其中包含文本和许多html标签,其中包含各自的属性及其值,例如: -
我正在尝试取出所有标记名称并推入数组注释: - 我有两个自定义函数,名为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));
这是我的想法,但它不起作用。
答案 0 :(得分:5)
更新;仅获取唯一标记(无重复)。
会让您走上从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);
答案 1 :(得分: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);