[英]accessing DOM elements by jQuery
假设我的代码片段中包含以下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>
的数组<p>.....</p>
??
你可以使用.get()
方法获得它
var arr = $("#t2").contents().get();
如果你检查小提琴,你会发现.contents()
返回一个由...组成的数组
text
和html
元素之类的
[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>');
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.