skramer
skramer

Reputation: 67

jQuery Find and replace with contents of a div

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

Answers (4)

Gerrit Bertier
Gerrit Bertier

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()));
        });
    }  

});

http://jsfiddle.net/KzCCQ/

Upvotes: 0

Ram
Ram

Reputation: 144669

You can use text method:

$('p').text(function(i, current){
   var c = $('.item-one').text();
   return current.replace('item one', c);
})

http://jsfiddle.net/3eE4G/

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)
})

http://jsfiddle.net/e7DRr/

Upvotes: 1

Igor Konopko
Igor Konopko

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

XCS
XCS

Reputation: 28137

$('p').text($('p').text().replace('item one',$('.item-one').text()));

jsFiddle link.

Tips:

  • If 'item-one' is unique use ID instead of class
  • You should also add an unique id to the <p>

Upvotes: 0

Related Questions