简体   繁体   English

使用.replace用javascript替换HTML字符串

[英]Replace HTML string with javascript using .replace

I have this html code: 我有这个HTML代码:

<p>Hello, this is a test replacing, <span class="myclass">over test</span> and <span class="myclass">over test</span>.</p>

My javascript works to replace the word "Hello" with "FuuBar". 我的javascript用于将“Hello”替换为“FuuBar”。

document.body.innerHTML = document.body.innerHTML.replace(/Hello/g, "FuuBar");

But I can not replace <span class="myclass">over test</span> by <span class="thanks"><b>Thanks God</b></span> 但我不能用<span class="myclass">over test</span> <span class="thanks"><b>Thanks God</b></span>替换<span class="myclass">over test</span> <span class="thanks"><b>Thanks God</b></span>

I am starting in javascript. 我是从javascript开始的。 I need to resolve this in pure js. 我需要在纯js中解决这个问题。 Could help in my code? 可以帮助我的代码吗? And sorry for the English. 抱歉英语。

JsFiddle for help. JsFiddle寻求帮助。

Use the DOM for this. 为此使用DOM。 Check here for more info: https://developer.mozilla.org/en-US/docs/DOM 点击此处获取更多信息: https//developer.mozilla.org/en-US/docs/DOM

var spans = document.querySelectorAll('.myclass');
for (var i=0; i<spans.length; i++) {
  spans[i].classList.remove('myclass');
  spans[i].classList.add('thanks');
  spans[i].innerHTML = '<b>Thanks god</b>';
}

Have you checked quotations? 你检查过报价了吗? You should escape them in the classname in JS or use single quotes. 您应该在JS中的类名中转义它们或使用单引号。 Please provide the code if that's not the case. 如果不是这样,请提供代码。

Other than that, replacing the whole body doesn't seem the best idea for a task like this. 除此之外,替换整个身体似乎不是这样的任务的最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM