Reputation: 67
I'm looking to find and replace text with jQuery, but found only simple functions that replaced static text with other static text. I wanted to figure out how to replace a string with the contents of another div. For Example:
<div class="item-one">blue</div>
<p>My color is item one</p>
What i want to do is replace the string "item one" with the contents of the div with a class of item-one. I want not just one instance of this string, but all of them on the page. I'd really appreciate any help with this. Thanks
Upvotes: 1
Views: 3463
Reputation: 4221
In case you want to have this fully dynamic, not caring about how many classes a div has, and how many times the div's content should be used.
$(document).ready(function()
{
var replaceClasses = [];
var currentClasses;
var i = 0;
// Save all classes to be used for replacement in an array
$('div').each(function()
{
currentClasses = $(this).attr('class').split(/\s+/);
for (i; i < currentClasses.length; i++)
{
replaceClasses.push(currentClasses[i].replace('-', ' '));
}
i = 0;
});
// Loop all classes and replace text if applicable
for (i; i < replaceClasses.length; i++)
{
var pText = $('p:contains("' + replaceClasses[i] + '")').text();
$('p:contains("' + replaceClasses[i] + '")').each(function()
{
$(this).text($(this).text().replace(replaceClasses[i], $('.' + replaceClasses[i].replace(' ', '-')).text()));
});
}
});
Upvotes: 0
Reputation: 144669
You can use text
method:
$('p').text(function(i, current){
var c = $('.item-one').text();
return current.replace('item one', c);
})
In case that you have more elements:
$('p').text(function(i, t) {
var w = t.split(' ')[4];
var c = $('.item-'+w).text();
return t.replace('item '+w, c)
})
Upvotes: 1
Reputation: 764
Trere two ways
First is to use .replace() function that can replace some static text to text from div like that:
$("p").text($("p").text().replace("text", $("#some_text").text()));
but better way is to take text what you want to change to "span" tag and use the text() function
$("p span").text($(".item-one").text());
Upvotes: 0
Reputation: 28137
$('p').text($('p').text().replace('item one',$('.item-one').text()));
Tips:
ID
instead of class<p>
Upvotes: 0