Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript查找元素的文本子级_Javascript - Fatal编程技术网

使用JavaScript查找元素的文本子级

使用JavaScript查找元素的文本子级,javascript,Javascript,我想使用纯JavaScript从以下DOM结构中查找文本片段“这是用于测试选择器的” <html> <body> <div class="breadcrumb"> <a title=" Home" href="http://www.google.com/"> Home</a> <span class="arrow">»</span>

我想使用纯JavaScript从以下DOM结构中查找文本片段“这是用于测试选择器的”

<html>
    <body>
        <div class="breadcrumb">
            <a title=" Home" href="http://www.google.com/"> Home</a> 
            <span class="arrow">»</span>
            <a title="abc" href="http://www.google.com/">test1</a> 
            <span class="arrow">»</span><a title="xyz" href="http://www.google.com/">test2</a> 
            <span class="arrow">»</span> 
            This is for testing selector
        </div>
    </body>
</html>

»
» 
» 
这是用来测试选择器的

我相信您需要这个答案中的代码:

但是,如果您不想使容器内容可编辑,只想使文本突出显示,则可以执行以下操作:

var textToHighlight = "This is for testing selector";
var breadcrumb = document.querySelector("#breadcrumb");
breadcrumb.innerHTML.replace(textToHighlight,
           "<span style='background-color:red'>" + textToHighlight + "</span>");
var textToHighlight=“这是用于测试选择器”;
var breadcrumb=document.querySelector(“breadcrumb”);
breadcrumb.innerHTML.replace(textToHighlight,
“+textToHighlight+”);

我认为可能有更简单的解决方案,但这同样有效:

var-element=document.getElementsByClassName(“面包屑”)[0];
var children=element.childNodes;
用于(儿童中的i){
if(文本的子[i]实例){
content=children[i].textContent;
如果(content.trim()!=“”){
警报(内容);
}
}
}

»
» 
»这是用于测试选择器

这应该可以做到

document.getElementsByClassName('breadcrumb')[0].lastChild;

请注意,只有当文本“这是用于测试选择器”保留为
breadcrumb

中的最后一个子项时,这才有效。如果要选择的文本始终位于
div.breadcrumb
标记中包装的所有标记之后,如您的示例所示,则使用以下方法:

document.querySelector('div.breadcrumb').lastChild.textContent.trim()

使用
querySelector
方法访问
div.breadcrumb
元素,然后访问该元素上的
lastChild
属性,该属性为您提供要查找的textNode。现在只需使用
textContent
属性获取该元素上的文本,最后使用
trim
方法去除前导空格和尾随空格以及换行符


JSoup是你的朋友。。。只有JavaScript你能澄清你的问题是什么你实际上在问什么?!使用java脚本选择器想要选择我提到的文本Nixkuroi我不想硬编码变量textToHighlight的值,你能通过任何选择器帮助检查和获取标记名或类名之类的东西吗。。。