2

I am having a variable with HTML content. Similar to "objHtml" variable below.

I want to replace a div tag with Id = 123 with another new div tag.

var objHtml = "<div> " +
"<div id='123' class='class1'>Text1</div>" + 
"<div id='124' class='class1'>Text2</div>" +
"</div>";

// I want to construct this new object using "objHtml", and want to replace div having id = 123 with div having id = 125.
// This Html is in the object and not visible or render on the page. 

var newObjHtml = "<div> " +
"<div id='125' class='class1'>Text5</div>" + 
"<div id='124' class='class1'>Text2</div>" +
"</div>";

Can any one answer how to replace an element in variable with another element?

2
  • 1
    Create a temporary element containing the elements within the string you have, then replace an element you want. After that you can get the HMTL of the temporary element. Commented Jun 20, 2015 at 13:08
  • Check this stackoverflow.com/questions/16590824/… Commented Jun 20, 2015 at 13:11

1 Answer 1

2

$(document).ready(function() {

  var objHtml = "<div> " +
    "<div id='123' class='class1'>Text1</div>" +
    "<div id='124' class='class1'>Text2</div>" +
    "</div>";

  //Create temporary element
  var elem = $(objHtml);
  
  //Find the element and replace it with new HTML
  elem.find('#123').replaceWith("<div id='125' class='class1'>Text5</div>");

  //Read outerHTML property and update your variable or create new variable
  objHtml = elem.prop("outerHTML");
  
  alert(objHtml)

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.