I have a webpage using jQuery. In this application, I have a function that takes an HTML string. This HTML line is dynamically generated. But I know that I want to update the list of classes on one of the HTML elements. An example HTML line 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 an element inside this row with a specific data id value and update its list of classes. To isolate my problem, I created this Fiddle , which includes 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 script, you will notice that the classes do not actually change. Why not? I can’t say what I am doing wrong. The example in Fiddle never changes from gray to green, as I expected based on the code above. What am I missing?