通过jQuery访问DOM元素

accessing DOM elements by jQuery

本文关键字:元素 DOM 访问 jQuery 通过      更新时间:2023-09-26

假设我的代码中有以下 DOM 元素:

<div id="test">
    <div id="t2">
       Hi I am
       <b>Gopi</b>
       and am 20 years old.
       <p id="div2">
         <button onclick="alert('lol')">Check</button>
       </p>
    </div>
</div>

假设我想遍历div#t2 的内容。

$("#t2").children()给了我<b><p>标签。

那么我应该如何访问它以获取包含" Hi I am","<b>....</b>","and am 20 years old.","<p>.....</p>"的数组的值

使用本机 DOM 节点:

$('#t2')[0].childNodes

为您提供所需的数组。

在使用 $.trim 之前,您可能也希望修剪条目,因为实际的文本节点包含 HTML 中的所有空格。

您可以使用

.get()方法获取它

var arr = $("#t2").contents().get();

工作小提琴

如果你检查小提琴,你会发现.contents()返回一个数组,包括

texthtml元素,如

 [text1,html1,text2,html2,text3]
 //Where
 text1 == Hi I am
 html1 == <b>Gopi</b>
 text2 == and am 20 years old. 
 html2 == <p id="div2"><button onclick="alert('lol')">Check</button></p>

这完全有道理,但最后text3从何而来。

标记末尾还有另一个文本节点<p>

 <p id="div2">....</p> <-- Here, newline is 
                           another text node(the last one)

因此,如果您使用.contents请记住这一点。

要获取修剪后的数据,请使用 $.map,例如

var arr = $("#t2").contents().map(function(){
 if (this.nodeType == 3)
     return $.trim(this.nodeValue) || null; 
                                     // this null to omit last textnode
 else
     return $('<div />').append(this).html();
 });
var result = [];
$("#t2").contents().map(function(index, el) {
    console.log(el);
    if(el.nodeType == 3) {
        result.push($.trim( $(el).text() ));
    } else {
        if(el.tagName.toLowerCase() == 'b') {
          result.push('<b>' + el.innerHTML + '</b>');
        } else if(el.tagName.toLowerCase() == 'p') {
          result.push('<p>' + el.innerHTML + '</p>');            
        }
   }
});

演示