0

How can you use jQuery to get rid of text between the <label> tags?

I would need to keep the <input> within the <label> but get rid of the "Clinical Vendor" text.

<label for="form">
    <input type="checkbox" class="ar" name="b" value="Clinical Vendor" id="form">Clinical Vendor
</label>

I have tried jQuery('label').text(''); but that seems to get rid of the input tag as well.

EDIT: Everyone came up with pretty much the same solution using nodes. TIL! Thanks, everybody!

qotsa42
  • 147
  • 1
  • 1
  • 11
  • 1
    The simplest way to do this is to wrap the text in another element, such as a `span`, then call `text('')` on that. If you want to keep your HTML as-is, you'll need to go filtering through the text nodes. – Rory McCrossan Oct 23 '18 at 16:16
  • 2
    Out of curiosity, why do you want to do this? – putvande Oct 23 '18 at 16:18
  • Possible duplicate of [jquery remove label text](https://stackoverflow.com/questions/46878456/jquery-remove-label-text) – Maarti Oct 23 '18 at 16:18
  • @putvande I am hacking together an interface using a Wordpress plugin. I don't have control of the HTML.... – qotsa42 Oct 23 '18 at 17:12

4 Answers4

2

An input tag can't have any child nodes since it is an empty element.
You need to target the text associated with the label and remove it.

About nodeType (MDN)

$('label')
  .contents()
  .filter(function() {
    return this.nodeType == 3;
  }).remove();

Code from this question

Quentin Veron
  • 3,079
  • 1
  • 14
  • 32
1

I believe this might work for you:

$("label").contents().filter(function(){ return this.nodeType != 1; }).remove();

Demo fiddle

Pedro Estrada
  • 224
  • 1
  • 6
0
jQuery('label').contents().last()[0].textContent='';
0

You could replace the text node with a blank one:

            function isTextNode() {
              return (this.nodeType === 3);
            }
            $("label").contents().filter(isTextNode).replaceWith(
              document.createTextNode("")
            );
mankowitz
  • 1,864
  • 1
  • 14
  • 32