Horen
Horen

Reputation: 11382

Changing child in jQuery does not persist in parent

I have the following code:

var data = "<div><p class='a'>Text</p></div>";
$(data).find(".a").each(function(){
    $(this).addClass("b");
})

console.log(data);   //will output: <div><p class='a'>Text</p></div> 
                     //instead of <div><p class='a b'>Text</p></div>

I'm iterating over a jQuery object $(data) and I'm changing the class of the child <p />. However, when I output the data after the change the class .b is gone.

Why is that so and how can I get this to work?

Upvotes: 0

Views: 165

Answers (4)

kiranvj
kiranvj

Reputation: 34107

In your case var data is a string.

But when you do $(data) its converted to a jQuery object and stored in memory. The new class b is added to the jQuery object not to the string data

You can try something like this

var data = "<div><p class='a'>Text</p></div>";

var $data = ""; // to store the jquery object

$data = $(data); // converts string to jQuery object

$data.find(".a").each(function(){
   $(this).addClass("b");   
})

console.log($data.get(0).outerHTML); //<div><p class='a b'>Text</p></div>

Upvotes: 1

user571545
user571545

Reputation:

I think you need to do something like this:

var data = "<div><p class='a'>Text</p></div>";
$(data).find('.a').each(function(){
    $(this).addClass("b");
}).appendTo('body'); //replace body with the target container

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

The reason is, you are not modifying the string data

When you say $(data) it creates a dom structure from the string and the dom is manipulared there after

Upvotes: 0

silly little me
silly little me

Reputation: 581

You need to store the result of the DOM element creation. The string itself is never modified.

var data = "<div><p class='a'>Text</p></div>";

// Create the elements from the markup
var elems = $(data);

// Modify the elements
elems.find(".a").each(function(){
    $(this).addClass("b");
});

// Append the elements to the DOM
elems.appendTo("body");

You can actually shorten your code to:

$(data).appendTo("body").find(".a").addClass("b");

Upvotes: 2

Related Questions