Javascript 使用jQuery获取DOM节点,然后将它们输出为逗号分隔的字符串
我试图获取所有DOM节点,然后将它们作为字符串输出,但输出是Javascript 使用jQuery获取DOM节点,然后将它们输出为逗号分隔的字符串,javascript,jquery,Javascript,Jquery,我试图获取所有DOM节点,然后将它们作为字符串输出,但输出是HTML集合format: [html, head, meta, title, body, h1, p] 相反,我希望将其输出为一个简单字符串: "html, head, meta, title, body, h1, p" 以下是我当前的jQuery: jQuery(document).ready(function($) { var allNodes = document.getElementsByTagName('*');
HTML集合
format:
[html, head, meta, title, body, h1, p]
相反,我希望将其输出为一个简单字符串:
"html, head, meta, title, body, h1, p"
以下是我当前的jQuery:
jQuery(document).ready(function($) {
var allNodes = document.getElementsByTagName('*');
console.log(allNodes);
});
正如@Taplar在我键入时指出的,您需要使用
Array\map
来检索标记名
属性。然而,还有一个非常小的额外步骤没有完成
HTMLCollection
s没有.map()
方法。为此,必须首先将HTMLCollection
转换为HTMLElement
s数组
不过,这项工作做得太多了。由于您已经在使用jQuery,更好的解决方案是将您的vanilla JS选择器更改为jQuery选择器,它可以将所有内容链接到一行中
jQuery(document).ready(function($) {
console.log($('*').get().map(v=>v.tagName).join(', '));
});
如果您对jQuery那么忠诚,您也可以使用$.map
,但我认为性能最好也一样
如果出于任何原因您不想在这里使用jQuery,我使用vanilla JavaScript的初步答案如下
jQuery(document).ready(function($) {
var allNodes = document.getElementsByTagName('*');
console.log(Array.from(allNodes).map(v=>v.tagName).join(', '));
});
一个使用jQuery(和三个普通JavaScript方法)的可重用解决方案,可以选择在一行中过滤掉标记(尽管是一个长行)
$(document).find('*')
$(document).find('*').not('style, script')
$(document).find('*').not('style, script').toArray()
:
$.map($(document).find('*').not('style, script').toArray(), (tag => tag.tagName))
$.map($(document).find('*').not('style, script').toArray(), (tag => tag.tagName)).join(', ');
JSON.stringify($.map($(selector).find('*').not(filter).toArray(), (tag => tag.tagName)).join(', ')).toLowerCase();
tagList(选择器,过滤器=null)
执行上述操作。第一个参数是父参数,第二个参数是可选的*——可以忽略
指数
指数
试验
const tagList=(selector,filter=null)=>JSON.stringify($.map($(selector.find('*')).not(filter.toArray(),(tag=>tag.tagName)).join(',')).toLowerCase();
log(标记列表(文档“脚本、样式”);
Somap()
他们的this.tagName
,然后加入他们的,“
@Taplar,谢谢……你能把代码写进答案吗?或者你能回答你自己的问题吗?:)哈哈……太好了,谢谢你。我很欣赏这个方向:)
JSON.stringify($.map($(selector).find('*').not(filter).toArray(), (tag => tag.tagName)).join(', ')).toLowerCase();