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.

0

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

and I'm gonna lose the anchor and whatnot
1

Yay, found it to work! Example :jsfiddle

var text = $('.outer').text();
$('.outer').text('').append($('<input>').val(text));

2 Comments

this in this context is not .outer, you're missing a ) and if you fix those problems this will be equivalent to the original code.
30 seconds before I posted according to the timestamps, caching issue I guess.
1

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

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

http://jsfiddle.net/9uQtJ/

Comments

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?.

Comments

0

Try something like this:

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

var text = $.trim($('.outer').text());
$('.outer').append($('<input>', {value: text}));

2 Comments

He doesn't want the text there anymore
@Phil -- and what about the link and the image?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.