如何使用jquery替换变量中的元素并在另一个变量中获取结果

时间:2015-06-20 13:02:17

标签: javascript jquery html

我有一个HTML内容的变量。类似于" objHtml"变量如下。

我想用另一个新的div标签替换Id = 123的div标签。

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>";

任何人都可以回答如何用另一个元素替换变量中的元素吗?

1 个答案:

答案 0 :(得分: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>