[英]How to loop through all elements in a div and find tags that contain text
I tried to loop through a div that contains all kind of elements. 我试图遍历包含所有元素的div。 The problem is, that I get the same results showing up in my example. 问题是,我在示例中也得到了相同的结果。
Here is the fiddle with the example code: http://jsfiddle.net/JLtCN/ 这是带有示例代码的小提琴: http : //jsfiddle.net/JLtCN/
So the html structure of my example looks like: 因此,我的示例的html结构如下所示:
<div class="somediv">
<span>hello</span>
<img src="someimg.jpg" width="20" height="20" />
<p></p>
<div><p>some text in a paragraph inside a div</p></div>
<h2>Some h2 tekst</h2>
<table>
<tbody>
<tr>
<td>some text in a table cell</td>
</tr>
</tbody>
</table>
</div>
My goal was to get all the content inside the html tags. 我的目标是将所有内容包含在html标签中。 like so, 像这样
tagtype: <span>, text: 'hello',
tagtype: <p>, text: 'some text in a paragraph inside a div'
etc.
Does anyone know how to do this correctly? 有人知道如何正确执行此操作吗?
Try this: 尝试这个:
$('.somediv *').each(function() {
var hastext = $(this).text().length != 0;
if(hastext) {
console.log("type: " + $(this)[0].tagName + " text: " + $(this).text());
}
});
DEMO: http://jsfiddle.net/JLtCN/1/ 演示: http : //jsfiddle.net/JLtCN/1/
If you want to get rid of the dupes, simply store the logged items in an array and then check if it's not in the array before logging, something like: 如果要摆脱重复,只需将记录的项目存储在数组中,然后在记录之前检查它是否不在数组中,例如:
Also, it now does them in reverse order so you get the lowest child instances only : 而且,现在它以相反的顺序进行操作,因此您只能获得最低的子实例 :
var addedItems = new Array();
$.each($('.somediv *').toArray().reverse(), function() {
var hastext = $(this).text().length != 0;
if(hastext && addedItems.indexOf($.trim($(this).text())) == -1) {
addedItems.push($.trim($(this).text()));
console.log("type: " + $(this)[0].tagName + " text: " + $(this).text());
}
});
DEMO: http://jsfiddle.net/JLtCN/3/ 演示: http : //jsfiddle.net/JLtCN/3/
Something like this: 像这样:
var seenStrings = [],
content = $.map(
$(".somediv *"),
function(element) {
var text = $(element).text();
if ($.inArray(text, seenStrings) !== -1) {
return {
tagname: "<" + element.nodeName.toLowerCase() + ">",
text: $(element).text()
};
} else {
return null;
}
}
);
var walk_the_DOM = function walk(node, func) {
func(node);
node = node.firstChild;
while (node) {
walk(node, func);
node = node.nextSibling;
}
};
walk_the_DOM(document.body, function(node) {
if(node.nodeType == 1){
document.write(node.nodeName + ": " );
}
if(node.nodeType == 3){
document.write(node.nodeValue +" <br/>");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.