Home > DeveloperSection > Forums > How do I update html element in a string inside an object?
Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    May-11-2013 2:26 AM

 JavaScript JavaScript 
Ratings:


 1 Reply(s)
 1011  View(s)
Rate this:
Hi All!

I'm having a hard time doing something that seems really simple. I have a javascript object:

var main = {
    pages : {
        "123" : {
            "content": "<div><p>The div</p></div><nav><p>The nav</p></nav>",
            "foo":"bar"
        },
        "456" : {
            "content": "<div><p>The div</p></div><nav><p>The nav</p></nav>",
            "foo":"bar"
        }
    }
};
I'm trying the following code:

$(function(){
        var p = main.pages;
        $.each(p,function(i,el){
            var c = p[i].content;
            var newc = $(c).find('nav').html('<p>New content</p>');
            //console.log(c);
            //console.log(newc);
        });
        //console.log(p)
});

To make my object look like:

var main = {
    pages : {
        "123" : {
            "content": "<div><p>The div</p></div><nav><p>New content</p></nav>",
            "foo":"bar"
        },
        "456" : {
            "content": "<div><p>The div</p></div><nav><p>New content</p></nav>",
            "foo":"bar"
        }
    }
};

But I'm having a hard time doing it. What am I missing?

I have set up the former example in jsfiddle

I do understand that it's generally not a good idea trying to manipulate strings as dom elements but I have no other choice since the object comes from a RESTful 

server and it doesn't make much sense to inject the html in the current page for that.

Thanks in advance! 



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-11-2013 9:55 AM

Hi Royce!

try as following. I hope it is helpful to you

$(function () {
    var p = main.pages;
    //a temporary div
    var div = $('<div>');
    $.each(p, function (i, el) {
        //append to div, find and replace the HTML
        div.append(p[i].content).find('nav').html('<p>New content</p>');
        //turn back into a string and store
        p[i].content = div.html();
        //empty the div for the next operation
        div.empty();
    });
    console.log(p);
});


Don't want to miss updates? Please click the below button!

Follow MindStick