[英]JavaScript select only inner html of outer element excluding inner element
I am trying to fetch inner html of an Element which has inner element like this我正在尝试获取具有这样的内部元素的元素的内部 html
<span> Hello How <span>a</span> re You</span>
I want fetch only Hello how re You but I am getting like this :我只想获取你好,你好吗,但我是这样的:
Hello How <span>a</span> re You
This is my javascript code:这是我的 javascript 代码:
<script>
$(document).ready(function(){
var spans = document.getElementsByTagName("span");
for(i=0;i<spans.length;i++){
alert(spans[i].innerHTML);
}
});
</script>
How can I solve this?我该如何解决这个问题?
You can either clone the element
then remove the child elements and get the contents or filter out the inner content您可以克隆element
然后删除子元素并获取内容或过滤掉内部内容
$(document).ready(function() { var $spans = $("span"); //first way $spans.each(function() { var text = $(this).clone().find('*').remove().end().text(); snippet.log('1: ' + text) }); //second way $spans.each(function() { var text = $(this).contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).text(); snippet.log('2: ' + text) }) });
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span> Hello How <span>a</span> re You</span>
In jquery way.以jquery的方式。
$(document).ready(function(){
var spans = document.getElementsByTagName("span");
for(i=0;i<spans.length;i++){
alert($(spans[i]).text()); // Changed here
}
});
Jsfiddle using jQuery使用 jQuery 的 Jsfiddle
Using javascript使用 JavaScript
$(document).ready(function(){
var spans = document.getElementsByTagName("span");
for(i=0;i<spans.length;i++){
alert(spans[i].textContent); // Using textContent
}
});
jsfiddle with javascript jsfiddle 使用 javascript
EDIT after comments If you are looking for only " Hello How a re You" you need to only retrieve the text form first NodeList
of span.评论后编辑如果您只查找“您好,您好”,您只需要检索跨度的第一个NodeList
文本表单。
In jquery way以jquery方式
$(document).ready(function(){
var sp = $('span');
alert($(sp[0]).text())
});
You can do it like this你可以这样做
alert($("span")[0].innerHTML.replace(/<(?:.|\\n)*>/gm, ''));
<span> Hello How <span>a</span> re You</span> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.