2

I have the markup like that:

<div class="outer">
  <a class="btn">
   <img src="btnImg.jpg" />
  </a>
  Some Title
</div>

Now, I need to replace the text (Some Title thing) with a textbox that contains the current title. I've tried that:

$(".outer").append("<input value='"+$(".outer").text()+"'></input>");
$(".outer").text("");

It puts a textbox with an empty string. I tried to store the text in a temporary variable, I tried to clone the entire outer div and then get the text, and empty the text in the original div. Anyway whatever I do, after I clear the text, input value also becomes empty.

Man of One Way
  • 3,904
  • 1
  • 26
  • 41
iLemming
  • 34,477
  • 60
  • 195
  • 309

5 Answers5

4

Simply store the text in a variable and then clear the div prior to appending the input.

var $outer = $(".outer");
var text = $.trim($outer.text());

$outer.empty();
$outer.append("<input value='" + text + "'></input>");

http://jsfiddle.net/SJeyf/2/

UPDATE based on comment (retain image, etc.):

var $outer = $(".outer");
var text = $.trim($outer.text());

var $textNode = $(".outer").contents()
                    .filter(function(){
                        return this.nodeType == 3 
                               && $.trim($(this).text()).length;   
                    }).eq(0)

$textNode.replaceWith("<input value='" + text + "'></input>");

http://jsfiddle.net/SJeyf/4/

NOTE: There may be a better way to grab the correct text node, but this seems to work.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
1

Yay, found it to work! Example :jsfiddle

var text = $('.outer').text();
$('.outer').text('').append($('<input>').val(text));
Phil
  • 10,948
  • 17
  • 69
  • 101
1

wow... that was an interesting excursion...

$(".outer")[0].lastChild.textContent = "blah";

http://jsfiddle.net/9uQtJ/

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

The problem is your last JavaScript statement. You replace all content of <div class="outer">…</div> with an empty string. The previous inserted input element is just removed.

You need to select only the text child nodes of <div class="outer">…</div> to remove "Some Title". Take a look at this question for how to do this: How do I select text nodes with jQuery?.

Community
  • 1
  • 1
knut
  • 4,699
  • 4
  • 33
  • 43
0

Try something like this:

http://jsfiddle.net/maniator/vsLac/

var text = $.trim($('.outer').text());
$('.outer').append($('<input>', {value: text}));
Naftali
  • 144,921
  • 39
  • 244
  • 303