Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.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(jquery)查找最内部的文本,而不考虑嵌套元素的数量,并替换它_Javascript_Jquery_Traversal - Fatal编程技术网

使用javascript(jquery)查找最内部的文本,而不考虑嵌套元素的数量,并替换它

使用javascript(jquery)查找最内部的文本,而不考虑嵌套元素的数量,并替换它,javascript,jquery,traversal,Javascript,Jquery,Traversal,如果我有这个: <a href="#" id="the-link"><em>any random text</em></a> 或者这个: <a href="#" id="the-link">any random text</a> <a href="#" id="the-link"><em><div id="foo"><span>any random text</s

如果我有这个:

<a href="#" id="the-link"><em>any random text</em></a>

或者这个:

<a href="#" id="the-link">any random text</a>
<a href="#" id="the-link"><em><div id="foo"><span>any random text</span></div></em></a>

或者这个:

<a href="#" id="the-link">any random text</a>
<a href="#" id="the-link"><em><div id="foo"><span>any random text</span></div></em></a>

我想捕获文本“任意随机文本”,然后替换它


如何使用jQuery实现这一点?如果不使用jQuery,只使用常规javascript?

您可能想查看以下问题:

看起来您需要找到最深的子项,然后在其上调用
.html('new string')
.text('new string')

$('a:contains(starcraft)').html('starcraft 2');
编辑以供评论:


您可以递归地执行此操作。这很简单:

function replaceTextNodes(node, newText) {
    if (node.nodeType == 3) {
        // Filter out text nodes that contain only whitespace
        if (!/^\s*$/.test(node.data)) {
            node.data = newText;
        }
    } else if (node.hasChildNodes()) {
        for (var i = 0, len = node.childNodes.length; i < len; ++i) {
            replaceTextNodes(node.childNodes[i], newText);
        }
    }
}

replaceTextNodes(document.getElementById("the-link"), "NEW TEXT");
函数replaceTextNodes(节点,newText){
if(node.nodeType==3){
//筛选出只包含空格的文本节点
if(!/^\s*$/.test(node.data)){
node.data=newText;
}
}else if(node.hasChildNodes()){
对于(变量i=0,len=node.childNodes.length;i
+1用于星际争霸,我最喜欢的游戏。这是DOM的一部分,或者一个字符串?如果文本可以是任何东西怎么办?@Amir-有关详细信息,请参阅小提琴示例