简体   繁体   中英

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):

<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"

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.

Something using the onload js method is preferable because the webpage is dynamically loaded.

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).

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

You can use JQuery which can easily change the content of the tags.

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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