-2

I have the below code in a website and I need to change the "Getting Started" text

<h4 data-v-318a1596="" class="h4">
  <div data-v-318a1596="">
    <i data-v-318a1596="" class="fa fa-check-square-o" style="color: rgb(141, 153, 166); font-size: 18px; margin-right: 6px;"></i> 
    Getting Started
  </div>
</h4>

As I have read here I tried to use textContent as below;

document.getElementsByClassName('h4')[0].childNodes[0].textContent='My text here'

The above code replaces the text but it also replaces the other HTML part specifically below;

<i data-v-318a1596="" class="fa fa-check-square-o" style="color: rgb(141, 153, 166); font-size: 18px; margin-right: 6px;"></i>

So after running my code the source looks like below;

<h4 data-v-318a1596="" class="h4"><div data-v-318a1596="">My text here</div></h4>

Could you please help me to replace only the text part?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 4
    Per the [docs](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent): "Setting textContent on a node removes all of the node's children and replaces them with a single text node with the given string value." – pilchard Nov 16 '20 at 10:56
  • 1
    You need to wrap the Getting Started text in a seperate element such as `span` in order to use `textContent` – Ozgur Sar Nov 16 '20 at 10:58

1 Answers1

1

You can change textNodes but you have to navigate the DOM to get there

const divToChange = document.querySelector(".h4 > div");
const textNode = divToChange.querySelector("i").nextSibling;
divToChange.replaceChild(document.createTextNode("Finish the job"),textNode)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />

<h4 data-v-318a1596="" class="h4">
  <div data-v-318a1596="">
    <i data-v-318a1596="" class="fa fa-check-square-o" style="color: rgb(141, 153, 166); font-size: 18px; margin-right: 6px;"></i> 
    Getting Started
  </div>
</h4>

It is of course simpler to have a span

If you can change that, then you can change the invalid h4 too

document.querySelector(".h4 > div > span").textContent = "Finish the job"
.h4 span { font-weight:bold }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />

<div data-v-318a1596="" class="h4">
  <div data-v-318a1596="">
    <i data-v-318a1596="" class="fa fa-check-square-o" style="color: rgb(141, 153, 166); font-size: 18px; margin-right: 6px;"></i> 
    <span>Getting Started</span>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236