2016-04-09 70 views
0

我試圖取代像HTML標籤中使用新文本的文本:的Javascript無法與HTML與新文本替換文本

text = " hello how are you? " ; 
    newText = "<h1>hello how are you? </h1> " ; 

這是我的代碼:

//replacer holds the html element 
var replacer = document.getElementById("#"+id); 

var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>"; 

//selectedinnerText holds the text to be replaced                 
alert(selectedinnerText + "  "+ newElement ); 

//This below line is not working properly 
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement); 
+0

在調試器,設置一個斷點在'VAR replacer'線,然後檢查跨過這句話後的價值。 –

回答

0

您的問題,當您通過JavaScript中的id獲取元素時,您不需要id名稱前面的

var replacer = document.getElementById(id); 

那麼,你爲什麼不能設置replacer元素的innerHTML的原因是因爲沒有存儲在變量現在元素。

0

正確的代碼應該是

var replacer = document.getElementById(id);// no # needed here 
var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>"; 

alert(selectedinnerText + "  "+ newElement ); 

replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);