如何将HTML标记的Jquery Selector转换为字符串值?

时间:2017-12-14 07:00:17

标签: javascript html css selector

我想将HTML标记的jQuery选择器转换为字符串值

所有HTML文档标记都有价值。

如何到达那里?

ex)

<!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

3 个答案:

答案 0 :(得分:0)

像这样使用jquery selector $(element)

注意:$('p[class^="txt_"]')这会选择p元素,其类别以txt_开头。

$(document).ready(function(){
  var allContent = $('p[class^="txt_"]');
  console.log(allContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!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>

答案 1 :(得分:0)

$('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并使用。
  5. 附加className来连接该行
  6. 替换“。”和字符串末尾的“\ s”(空格)字符表示没有类的标签,最后没有点

答案 2 :(得分:0)

您可以使用它来使用class获取字符串文本值。喜欢 $(”。txt_1' )文本()。 这是p标签类

的一个p标签文本

$('。contents p')。text() 这适用于div中的所有p标记