[英]How to replace text inside specific elements using javascript or any other qualified language?
I have this block of HTML(i don't want to change the code): 我有这个HTML块(我不想更改代码):
<section class="welcome-block-top">
<div class="inside">
<h2>Start a good life</h2>
<label>text to replace 1</label>
<a href="" class="link-a">
some text i do not want to replace</a>
</div>
</section>
i want to replace the text "text to replace 1" 我想替换文字“替换文字1”
i also want to replace text here: 我也想在这里替换文字:
<h3>
<span>
text to replace 2 </span>
</h3>
please teach me masters, i searched Google and stack-overflow and i dont seem to get something that works in my situation. 请教我高手,我搜索了Google和堆栈溢出,但我似乎没有找到适合我的情况的东西。
Something using the onload js method is preferable because the webpage is dynamically loaded. 最好使用onload js方法,因为网页是动态加载的。
if you know a better method to do this with any other language don't hesitate to inform me. 如果您知道使用其他任何语言的更好方法,请随时通知我。
If there is a method to clear the text inside the elements and then insert new text i would be grateful. 如果有一种方法可以清除元素内的文本,然后插入新文本,我将不胜感激。
It depends on your real use case but it might be this : 这取决于您的实际用例,但可能是这样的:
$('*:not(:has(*))').text(function(_,t){
return t.replace("text to replace 1", "replacement")
});
The main idea here is to apply a transformation to the text of all elements with no children (leafs in the DOM tree). 这里的主要思想是对没有子元素的所有元素(DOM树中的叶子)的文本进行转换。
If you have more complex needs, or performance requirements, you might want to have a look at dedicated libraries, like mine : https://github.com/Canop/groumf 如果您有更复杂的需求或性能要求,则可能需要查看专用的库,例如我的库: https : //github.com/Canop/groumf
You can use JQuery which can easily change the content of the tags. 您可以使用JQuery ,它可以轻松更改标签的内容。
oldContent = $("div.inside label:first").html();
$("div.inside label:first").html("put your desired content here");
meaining that find first
label
tag in the div
tag having inside
class and change its html
content with the parameter. 这意味着在具有
inside
类的div
标签中找到first
label
标签,并使用参数更改其html
内容。
EDIT: 编辑:
You can of course save the old content and use it. 您当然可以保存旧内容并使用它。
$("div.inside label:first").html(oldContent + " new content");
or 要么
$("div.inside label:first").append(" new content");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.