user687554 user687554 - 6 months ago 54
Javascript Question

jQuery - Update string of HTML

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?


You don't need to update html. You can just add the classes like following.

function updateClass() {
    var $elm = $('#myElement'); 
    updateHtml($elm, 1)

function updateHtml($elm, id) {  
    var leaf = $elm.find('div[data-id="' + id + '"]');
    if (leaf) {
        $(leaf).addClass('example complete');  
.example {
    border: solid 2px #000;

.complete {
<script src=""></script>
<div class="container">
    <div id="myElement">
        <p>This is a test</p>
        <div class="example" data-id="1">example</div>     
        <p>This is only a test.</p>
    <br />

    <button class="btn btn-primary" onclick="updateClass()">