How to add a class in html elements of a string?

2

The scenario is as follows: I dynamically add an html. Once the html is generated it gets +/- like this:

var templateHtml = "<div class='bola'>Bola 1</div><div class='bola'>Bola 2</div><div class='casa'>Casa 1</div>";

I'd like to add the "soccer" class in all the divs with the "ball" class.

I tried this way:

templateHtml = $(templateHtml).find(".bola").addClass("futebol");

But it did not work ....

    
asked by anonymous 16.01.2015 / 14:33

1 answer

2

Replace method call find with filter .

templateHtml = $(templateHtml).filter(".bola").addClass("futebol");

filter filters the selected elements and find looks within them. What happens is that when you pass the html as a string the selected elements are the ones that are in the first layer.

For example:

console.log($("<div id='div1'></div><div id='div2'></div>")); // [div#div1, div#div2]

// com a sua variável
console.log($(templateHtml)); // [div.bola, div.bola, div.casa]
    
16.01.2015 / 14:39