HOW DO I UPDATE HTML ELEMENT IN A STRING INSIDE AN OBJECT?

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
 1303  View(s)
Ratings:
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! 

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: How do I update html element in a string inside an object?

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!