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

Asked

Viewed 825 times

2

The scenario is as follows: I dynamically assemble an html. After the html is generated it is +/- like this:

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

I would like to add the class "football" in all Divs with the class "ball".

I tried so:

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

But it didn’t work....

1 answer

2


Replace the method call find for filter.

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

The filter filters the selected elements and the find searches within them. What happens is that when you pass html as a string the selected elements are the ones 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]
  • That’s right! But why does filter return html and find no? I haven’t figured that out yet.

  • 1

    @Joaopaulo I edited the answer. I hope it became clearer =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.