0

There's a label and an input element.

<div id="mydiv" class="my-div-class"><label id="id-label">abc<input type="text" id="id-text"></label></div>

Now I want to change the label's text (E.g. from abc to efg)

This doesn't change it:

$('#id-label').html('efg');

And this makes the input disappear:

$('#id-label').html('efg');

$('#id-label').html('efg');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv" class="my-div-class"><label id="id-label">abc<input type="text" id="id-text"></label></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
smolo
  • 737
  • 1
  • 15
  • 27
  • 1
    `html(...)` - this overwrites the inner html of the selected element. In your case, since `input` is a child of the `label`, it gets overwritten. One way to solve this problem is to make `input` a sibling element of the `label`. – Yousaf Jul 06 '21 at 09:47
  • Do you have more than one label with the same ID? – VLAZ Jul 06 '21 at 09:48
  • There's just one label with the same ID. – smolo Jul 06 '21 at 09:51

1 Answers1

2

Your input element is inside the label so you will wipe the content

This will work better

NOTE: If the label does not have the need for any markup, use .text() instead of .html

$('#id-label').text('Prompt: ');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv" class="my-div-class">
  <label id="id-label" for="id-text">abc</label>
  <input type="text" id="id-text">
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    And it's probably better to use `.text('efg')` if it's just being set to plain text. – DBS Jul 06 '21 at 09:51