我想从没有类名的span元素中提取文本。怎么做到呢? 可以搜索具有特定类名的元素,但是如何只获取没有类名的元素?
<span>0m2abBrL+RIHOEA+dZS+OqV3St+nJ/</span>
<wbr></wbr>
<span class="word_break"></span>
<span>zwq73Gfz8MQGB0yS++lfufSOV133huE</span>
<wbr></wbr>
<span class="word_break"></span>
vCB0s5D9w
<span class="text_exposed_hide">...</span>
答案 0 :(得分:3)
通过它们迭代并检查我想的类名。
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
if (spans[i].className == '') {
//span doesn't have a class
}
}
答案 1 :(得分:1)
可以进行更多优化..但这就是你如何做到这一点..
function getElementsByNoClassName() {
var node = document.getElementsByTagName("body")[0];
var a = [];
var els = node.getElementsByTagName("*");
for (var i = 0, j = els.length; i < j; i++)
if (els[i].className=='') a.push(els[i]);
return a;
}
答案 2 :(得分:0)
尽管我发现它有多烦人,但我会给出一个jQuery答案(因为mrtsherman用一个真正的答案打败了我):
$('span:not([class])')
答案 3 :(得分:0)
使用Element.querySelectorAll
,您可以使用以下代码来实现此目的。
document.getElementsByTagName('span').querySelectorAll('span:not([class])');
答案 4 :(得分:-1)
在我的朋友投票后,我在核心java脚本中添加了代码:
<html>
<head>
<style>
span{display:block;}
</style>
<script type="text/javascript">
function getElementsByNoClassName() {
var node = document.getElementsByTagName("span");
console.log(node.length);
var a = [];
for (var i = 0, j = node.length; i < j; i++){
if (node[i].className=='')
node[i].setAttribute("style","color:red;");
}
}
window.onload=getElementsByNoClassName;
</script>
</head>
<body>
Content with No class is colored in red.
<span>0m2abBrL+RIHOEA+dZS+OqV3St+nJ/</span>
<wbr></wbr>
<span class="word_break"></span>
<span>zwq73Gfz8MQGB0yS++lfufSOV133huE</span>
<wbr></wbr>
<span class="word_break"></span>
vCB0s5D9w
<span class="text_exposed_hide">...</span>
</body>
</html>
这也可以通过jQuery来完成:
<html>
<head>
<style>
span{display:block;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("span").filter(
function(){
return $(this).attr('class')==undefined
}).css('color','red');
});
</script>
</head>
<body>
Content with No class is colored in red.
<span>0m2abBrL+RIHOEA+dZS+OqV3St+nJ/</span>
<wbr></wbr>
<span class="word_break"></span>
<span>zwq73Gfz8MQGB0yS++lfufSOV133huE</span>
<wbr></wbr>
<span class="word_break"></span>
vCB0s5D9w
<span class="text_exposed_hide">...</span>
</body>
</html>