Cliff
Cliff

Reputation: 707

Remove text that doesn't have its own element

I have some HTML that looks like this:

<div class="field">
    <input type="text" name="name" id="sourcedidSource" value="SYSTEM">SYSTEM
    <span class="someClass"></span>
</div>

I need to remove the SYSTEM text after sourcedidSource while keeping everything else intact. I tried $('.field').text().remove();, but that removes the input and span elements as well. What should I do?

Upvotes: 3

Views: 209

Answers (4)

adeneo
adeneo

Reputation: 318182

It's actually a lot easier to work with textnodes without jQuery

var node = document.getElementById('sourcedidSource').nextSibling;
node.parentNode.removeChild(node);

Or the funky jQuery version

$($('#sourcedidSource').get(0).nextSibling).remove();

Upvotes: 3

An0nC0d3r
An0nC0d3r

Reputation: 1303

Instead of $('.field').text().remove();

Do $('#sourcedidSource').text('') OR $('#sourcedidSource').text().remove()

This will target the specific input field you have and set the text content to an empty string, ''.

Upvotes: 0

Nigrimmist
Nigrimmist

Reputation: 12358

There is your solution : https://jsfiddle.net/yuswddpg/

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

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use contents() and filter() to get the textNode within the .field and remove() them. Try this:

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

Example fiddle

Upvotes: 2

Related Questions