I have a web page that uses jQuery. In this app, I have a function that takes in an HTML string. This HTML string is dynamically generated. But, I know I want to update the class list on one of the elements in the HTML. An example of the HTML string would be something like this:
<p>This is a test</p><div class="example" data-id="1">example</div> <p>This is only a test.</p>
I want to find the element within this string with a specific data-id value, and update its class list. In an effort to isolate my issue, I've created this Fiddle, which include the following code:
function updateHtml(html, id) {
var tree = $(html);
var updatedHtml = html;
var leaf = $(tree).find('div[data-id="' + id + '"]');
if (leaf) {
$(leaf).attr('class', 'example complete');
updatedHtml = $(tree).html();
}
return updatedHtml;
}
When you run the Fiddle, you'll notice that the classes do not actually change. Why not? I can't tell what I'm doing wrong. The example in the Fiddle never changes from gray to green like I'd expect based on the code above. What am I missing?