Swapping text in a DOM element with children JavaScript/jQuery

青春壹個敷衍的年華 提交于 2021-02-19 09:02:21

问题


So I have a DOM element that looks like this:

<span>text</span>
<b>some more text</b>
even more text here
<div>maybe some text here</div>

My question is how do I swap text for candy so it looks like this:

<span>text</span>
<b>some more text</b>
even more *candy* here
<div>maybe some text here</div>

I've tried a .replace with regex already but it swaps all the text occurrences.

Also I do not know where the text without tags will be. It could be in the middle at the beginning or at the end, (basically anywhere) I can't remove the child nodes either, because I don't know their positions and also if there is a <script> child it would probably rerun when I add it again at the end of all the text manipulation.

Can anyone point me in the right direction?


回答1:


You can check the nodeType property of the nodes:

$('#parent').contents().each(function() {
   if (this.nodeType === 3) {
      this.nodeValue = this.nodeValue.replace('text', 'candy');
   }
});

If you want to replace the text with HTML, you can use the replaceWith method:

$('#parent').contents().filter(function() {
   return this.nodeType === 3 && this.nodeValue.indexOf('text') > -1;
}).replaceWith(function() {
    return this.nodeValue.replace(/(text)/g, '<strong>candy</strong>');
});



回答2:


Looks like I got beaten to the button, so here is an alternative way. I'm assuming all of those elements are enclosed in somesort of parent element, such as 'enclosingDiv'. If that is so, a simple answer would be:

    var e = document.getELmentById('enclosingDiv');

    var divAsString = String(e);
    var newDivAsString = divAsString.replace('text', 'candy');
    e.innerHTML = newDivAsString;


来源:https://stackoverflow.com/questions/24965295/swapping-text-in-a-dom-element-with-children-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!