Reputation: 3
I have a div with some text
<div>This is my initial text</div>
And I'd like to replace the text 'initial' with an input box which I already have created
Something like:
input=$("#myinput");
$("div").find("initial").replaceWith(input);
OR:
input=$("#myinput");
$("div").html().replace('initial',input);
But neither of these work
Any thoughts?
Upvotes: 0
Views: 96
Reputation: 318212
var input = $("#myinput");
$("div:contains(initial)").replaceWith(input);
EDIT:
to replace just the word "initial" :
var input = $("#myinput");
$("div:contains(initial)").html(function(_,html) {
return html.replace('initial', input.get(0).outerHTML);
});
Upvotes: 0
Reputation: 17139
Why not surround it with a span so that it's easier to find:
<div>This is my <span id="replace">initial</span> text</div>
Then:
$('#replace').replaceWith(input);
Upvotes: 5
Reputation: 20757
This ought to work:
$("div").html(input)
EDIT: actually, no, it won't, you need to wrap "initial" with some sort of element, preferably with an "id" or "class" element so you can select it directly.
EDIT #2:
// Grab the actual HTML of the element you want to inject
var elementHTML = $(input).html();
// Loop over each DIV, though you really should use ID/class attributes
$("div").each(function() {
var divHTML = $(this).html(); // Grab a copy of the DIV's HTML
$(this).html(divHTML.replace('initial', elementHTML)); // Replace "initial" in the saved string with the element's HTML from above
});
Upvotes: -2
Reputation: 12985
Try:
$("div").html($('div').text().replace('initial',input.html()));
Though I like this better if your jQuery is new enough:
$("div").html($.parseHTML($('div').text().replace('initial',input.html())));
Upvotes: 2