user687554 user687554 - 16 days ago 4
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?

Answer

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 {
    background-color:lightgray;
    border: solid 2px #000;
    padding:12px;
}

.complete {
    background-color:green;
    color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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>
    </div>
    <br />

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