![](/img/trans.png)
[英]Idiomatic jQuery to get all options in a listbox into comma-separated string?
[英]Get DOM nodes using jQuery, then output them to comma-separated string
我正在尝试获取所有DOM节点,然后将它们输出为字符串,但是输出为HTML Collection
格式:
[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
检索tagName
属性。 但是,缺少一个非常小的额外步骤。
HTMLCollection
没有.map()
方法。 为了解决这个问题,您必须HTMLCollection
转换为HTMLElement
的数组。
但是,这比价值还多。 由于您已经在使用jQuery,因此更好的解决方案是将Vanilla JS选择器更改为jQuery选择器,该选择器可以将所有内容链接在一起。
jQuery(document).ready(function($) {
console.log($('*').get().map(v=>v.tagName).join(', '));
});
如果您忠于jQuery,也可以使用$.map
,但是我认为性能最好是相同的 。
jQuery(document).ready(function($) {
console.log($.map($('*'),v=>v.tagName).join(', '));
});
如果您出于某种原因不想在这里使用jQuery,则下面是我使用原始JavaScript的初步答案。
jQuery(document).ready(function($) {
var allNodes = document.getElementsByTagName('*');
console.log(Array.from(allNodes).map(v=>v.tagName).join(', '));
});
一种使用jQuery(和三种Plain JavaScript方法)的可重用解决方案,并且可以选择在一行中过滤掉标签(尽管很长)。
查找文档的所有标签:
$(document).find('*')
过滤所有不需要的标签*:
$(document).find('*').not('style, script')
将jQuery Collection转换成数组:
$(document).find('*').not('style, script').toArray()
映射数组,并从每个元素返回tagName
:
$.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(selector, filter = null)
完成上述操作。 第一个参数是父级,第二个参数是可选*-可以忽略。
<html> <head> <meta charset='utf-8'> <title>Index</title> </head> <body> <h1>Index</h1> <p>Test</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> const tagList = (selector, filter = null) => JSON.stringify($.map($(selector).find('*').not(filter).toArray(), (tag => tag.tagName)).join(', ')).toLowerCase(); console.log(tagList(document, 'script, style')); </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.