A

B...">

JQuery change html value which is stored in a variable

I have html code stored in myHtml variable

<div>
    <p data-id="1">A</p>
    <p data-id="2">B</p>
    <p data-id="3">C</p>
</div>

      

I need to change the value before adding this to the html.

My code doesn't change value

$(myHtml).find('p[data-id="1"]').text("new text");

      

Also consider changing the src of the image, for example

<img src="image.jpg" />

      

So I need something like

$(myHtml).find('img').attr("src", "new-image.jpg");

      

Thank you in advance

+3


source to share


1 answer


You need to wrap myHtml

with with $

to apply jQuery code

$(myHtml).find('p[data-id="1"]').text("new text");

      

To get this updated value use the following method,



var myHtml = '<div>' +
  '<p data-id="1">A</p>' +
  '<p data-id="2">B</p>' +
  '<p data-id="3">C</p>' +
  '</div>';
myHtml = $(myHtml).find('p[data-id="1"]').text("new text").end()[0].outerHTML;
alert(myHtml);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>
      

Run codeHide result


+6


source







All Articles