Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 649
Robyflc Avatar asked Sep 07 '26 04:09

Robyflc


2 Answers

You can actually build the HTML in jQuery without appending it into the DOM.

$(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);
});
like image 75
Joseph Avatar answered Sep 10 '26 08:09

Joseph


Because $(p[i].content) is not one element but two, so based on your code:

var tmp = $(p[i].content);
tmp.eq(1).html('<p>new content');
console.log(tmp.html());
like image 32
Kabie Avatar answered Sep 10 '26 08:09

Kabie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!