Natesan
Natesan

Reputation: 1145

Remove text which is not in any tag

I have the html code look like this

<form id="form1">
    <img src="..." />
    <input type="text" value="Text box 1" id="txt1" />
    Sample text
    <input type="hidden" value="name" />
</form>

I want to remove the text Sample text which is not in any tag.

How to remove this text?

Upvotes: 1

Views: 114

Answers (3)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$(function(){
    var html=$('#form1').html();
    var txt=$('#form1').text();
    html=html.replace($.trim(txt),'');
    $('#form1').html(html);
});

Working fiddle

Upvotes: 0

Pranav
Pranav

Reputation: 8871

try this ..it is working :-

$(document).ready(function(){
     var $tmp = $('#form1').children().remove();
     $('#form1').text('').append($tmp);
});

see the FIDDLE

Upvotes: 0

Damien
Damien

Reputation: 8987

This works :

$('#form1')
  .contents()
  .filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
  }).remove();

See fiddle

Upvotes: 2

Related Questions