JQuery - update HTML string

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?

+4
3

html. , .

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>
Hide result
+1
function updateHtml(html, id) {
  $('div[data-id="' + id + '"]').addClass("complete").html(html);
}
0

I checked your example in Fiddle and made the following updates, you can try the following code and it should work.

<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="return updateClass();">
    Run
  </button>
</div>
<script>
function updateClass() {
  var html = $('#myElement').html();
 
  var newHtml = updateHtml(html, '1');
  $('#myElement').html(newHtml);  
}

function updateHtml(html, id) {
    
  var updatedHtml = html;
  var $html = $('<div />',{html:html});
  $html.find('div[data-id="' + id+'"]').addClass("example complet");
    
  return $html;
}
</script>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1661754/


All Articles