Khadim Ali Khadim Ali - 5 months ago 16
jQuery Question

How to select text between html <label> element

Given following html:

<label for="xxxx" id="Password_label">
<div class="xxxx">Password 555</div>
555
<div class="xxx"></div>
</label>


I need to replace the text "555" written inside the label element below the first div. I am trying to get the text but not able to do so far.

I tried:

$("#Password_label").text()


But it is returning empty string.

Answer

Get the text node with help of contents() and eq() then replace the text using replaceWith().

$('#Password_label')
  .contents() // get all nodes including text node
  .eq(2) // get the text node 
  .replaceWith('newText') // replace with new content
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="xxxx" id="Password_label">
  <div class="xxxx">Password 555</div>
  555
  <div class="xxx"></div>
</label>


With pure JavaScript use childNodes to get all child nodes and update text content using textContent property of node.

document.getElementById('Password_label') // get element by id
  .childNodes[2] // get all childnodes and get text node need to update
  .textContent = 'newText'; // update text content of that node
<label for="xxxx" id="Password_label">
  <div class="xxxx">Password 555</div>
  555
  <div class="xxx"></div>
</label>


UPDATE : If there is only one text node then

$('#Password_label')
  .contents() // get all nodes including text node
  .filter(function() { // filterout non-empty text nodes
    return this.nodeType === 3 && $.trim(this.textContent).length;
  })
  .replaceWith('newText') // replace with new content
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="xxxx" id="Password_label">
  <div class="xxxx">Password 555</div>
  555
  <div class="xxx"></div>
</label>