0

I have a HTML which looks like:

enter image description here

I want to replace the word Search: with another word some word. How can I do this? I tried:

document.querySelector("#state-covid-data_filter label").innerText = "some word"

but this also replaces the input tag.

I also tried:

document.querySelector("#state-covid-data_filter label").innerHTML = document.querySelector("#state-covid-data_filter label").innerHTML.replace("Search:","Some word:")

But then the input tag loses the events registered. How could I just replace the text such that everything else remains fine.

Amanda
  • 2,013
  • 3
  • 24
  • 57
  • Wrap it in a ``. (If you cannot change the HTML, get the textNode child and change that) –  Jul 22 '20 at 08:24
  • Does this answer your question? [How can I change an element's text without changing its child elements?](https://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child-elements) – Liam Jul 22 '20 at 08:24

3 Answers3

1

You can get the text node by childNodes.

If the text is always at the beginning of the element, you can just change it like this:

document.querySelector('label').childNodes[0].textContent = 'Some word:';
<label>
  Search:
  <input type="text" />
</label>
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
0

A workaround would be to redraw the label, it would account for the scenarios when your label may not have any text content to begin with, or when it's placed after the input

const label = document.querySelector("label");
const input = label.querySelector("input");
label.innerHTML = "NEW STRING";
label.append(input);
Rubens
  • 341
  • 1
  • 6
-2

Because your input is inside your label it is also part of the innerText you can add a element around the text and select that instead like this

document.querySelector("#your_id label span").innerText = "some word";
<div id="your_id">
  <label for="">
    <span>Your text</span>
    <input type="search">
  </label>
</div>
Nico Shultz
  • 1,872
  • 1
  • 9
  • 23