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, a开发者_JS百科fter I clear the text, input value also becomes empty.
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.
Yay, found it to work! Example :jsfiddle
var text = $('.outer').text();
$('.outer').text('').append($('<input>').val(text));
wow... that was an interesting excursion...
$(".outer")[0].lastChild.textContent = "blah";
http://jsfiddle.net/9uQtJ/
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?.
Try something like this:
http://jsfiddle.net/maniator/vsLac/
var text = $.trim($('.outer').text());
$('.outer').append($('<input>', {value: text}));
精彩评论