Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change html value that is saved in variable

I have html code saved in a variable called myHtml

<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 of before appending this to html.

My code doesn't change the value

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

Also need to consider changing src of an image like

<img src="image.jpg" />

So I need something like

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

Thanks in advance

like image 214
Ediboy Ilagan Avatar asked Sep 15 '25 11:09

Ediboy Ilagan


1 Answers

You need to wrap myHtml with $ for applying jQuery code

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

To get that updated value use 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>
like image 81
Pranav C Balan Avatar answered Sep 17 '25 00:09

Pranav C Balan