javascript - Javascript - 更改<p>中的文本而不影响<span>中的其余部分

我尝试使用Tampermonkey为Chrome编写用户脚本,


function run () {


 var target = document.querySelector('#dipContainer dip-info-top div.new-dip-info div.col-md-4 div:nth-child(2) div:nth-child(1) p')


 if (target) {


 var str = target.innerHTML;


 str = str.replace(" String to find","Shortened");


 target.innerHTML = str;


 } else {


 setTimeout(run, 500);


 }


 }


//The below detect any time the <p> changes and run the code to shorten the term. It works.


waitForKeyElements (


"#dipContainer dip-info-top div.new-dip-info div.col-md-4 div:nth-child(2) div:nth-child(1) p",


 run


);


})();



不幸的是,<p>还包含了一些其他代码,以后我要缩短字符串,这样可以点击一些统计信息。


<span class="player-info-stat">


 <a class="badge ng-binding disabled" ng-class="{'disabled': history.itemModerationCount === 0}" ng-click="history.itemModerationCount > 0 ? openHistoryModal('itemHistory') : null" data-ol-has-click-handler="">0</a>


</span>



时间:

搜索文本节点并将它node值设置为替换的文本,而不是替换innerHTML


// https://stackoverflow.com/questions/2579666/



function nativeTreeWalker(parent) {


 var walker = document.createTreeWalker(


 parent,


 NodeFilter.SHOW_TEXT,


 null,


 false


 );



 var node;


 var textNodes = [];



 while (node = walker.nextNode()) {


 textNodes.push(node);


 }


 return textNodes;


}



document.querySelector('p').addEventListener('click', () => console.log('p clicked'));


const textNodes = nativeTreeWalker(document.querySelector('#div'));


textNodes.forEach((textNode) => {


 textNode.nodeValue = textNode.nodeValue.replace(/text/g, 'replaced');


});

<div id="div">


 text


 <p>clickable</p>


 text


</div>

...