2015-06-20 42 views
1

我有一個HTML內容的變量。類似於下面的「objHtml」變量。如何使用jQuery替換變量中的元素並在另一個變量中獲取結果

我想用另一個新的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

創建一個包含有你在字符串中的元素的臨時元素,然後更換你想要的元素。之後,您可以獲取臨時元素的HMTL。 – Teemu

+0

檢查此問題http://stackoverflow.com/questions/16590824/jquery-selector-inside-of-variable – Boris

回答

1

$(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>

相關問題