• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Can I change only a part of innerHTML with JavaScript

Johna

HTML, CSS and JS Coder
Staff Team
Guardian
I want to change only a part of innerHTML with JavaScript, for example this:

HTML:
<html>
    <head>
        <title>Example</title>
    </head>
   
    <body>
        <p id="text">This is an example</p>
        <button onclick="myFunction()">Click to change 'an' to 'my'</button>
    </body>
   
    <script>
        function myFunction() {
            document.getElementById('text').innerHTML = /*Here I want to change only the 'an' to 'my', so it's 'This is my example'. Is there a way to do that?*/
        }
    </script>
</html>

Is is even possible to do something like this?

Thanks : )
 
Solution
Thanks, but what if I want to change the html of a website, like with a chrome extension, so the text doesn't have a span around it. Can I do that or is that not possible?
Looks like it is possible without the span element actually.

JavaScript:
function myFunction() {
  document.getElementById('text').innerHTML = document.getElementById('text').innerHTML.replace("an", "my");
}

This would essentially replace the text with the same text but after changing the "an" word to "my".

Credit to this post on Stack Overflow.

Ash

King Coder
Maybe someone has a simpler solution but I would simply add a span element for the "an" text. Then you can just change the contents of that element.

HTML:
<p id="text">This is <span id="changeText">an</span> example</p>

JavaScript:
function myFunction() {
    document.getElementById('changeText').innerHTML = "my";
}
 

Johna

HTML, CSS and JS Coder
Staff Team
Guardian
Thanks, but what if I want to change the html of a website, like with a chrome extension, so the text doesn't have a span around it. Can I do that or is that not possible?
 

Ash

King Coder
Thanks, but what if I want to change the html of a website, like with a chrome extension, so the text doesn't have a span around it. Can I do that or is that not possible?
Looks like it is possible without the span element actually.

JavaScript:
function myFunction() {
  document.getElementById('text').innerHTML = document.getElementById('text').innerHTML.replace("an", "my");
}

This would essentially replace the text with the same text but after changing the "an" word to "my".

Credit to this post on Stack Overflow.
 
Solution
Top