forum

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

How do I update html element in a string inside an object?

Royce Roy226711-May-2013
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! 


Updated on 11-May-2013

Can you answer this question?


Answer

1 Answers

Liked By