gpt4 book ai didi

javascript - 如何将 HTML 标记的 Jquery 选择器获取到字符串值?

转载 作者:行者123 更新时间:2023-11-28 02:28:45 25 4
gpt4 key购买 nike

我想获取 HTML 标签的 jQuery 选择器为字符串值

所有 HTML 文档标签值。

怎么去?

例如)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="contents">
<p class="txt_1">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
<p class="txt_2">Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>
<p class="txt_3">It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
</body>
</html>

导出)

div.contents
p.txt_1
p.txt_2
p.txt_3

最佳答案

$('body *').get().map(function(v){
var line = v.tagName.toLowerCase() + '.' + (v.getAttribute('class') || '');
return line.replace(/[\.\s]+$/, '');
});

没有jquery

[].map.call(document.querySelectorAll('body *'), function(v){
var line = v.tagName.toLowerCase() + '.' + (v.getAttribute('class') || '');
return line.replace(/[\.\s]+$/, '');
});
  1. 通过选择 body * 获取所有 DOM 节点(星号匹配所有节点)
  2. 可选:调用 jquery 对象的 get 方法返回一个裸数组
  3. 在数组上运行 map 以将其节点转换为所需的字符串
  4. 通过获取 tagName 并附加以 . 分隔的 className 来连接该行。
  5. 替换“.”和字符串末尾的“\s”(空白)字符表示没有类的标签,末尾没有点

关于javascript - 如何将 HTML 标记的 Jquery 选择器获取到字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47807611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com