2016-06-08 49 views
0

除非我犯了一個錯誤,否則我沒有找到一個乾淨/簡單的答案來解決我的問題。如何使用javascript或angularjs從html標籤中提取/編輯屬性?

我有一個字符串,幷包含一個src屬性的標籤:

var str = "<iframe src="https://www.google.com/" height="800" width="500"></iframe>" 

使用JS或AngularJS(!ONLY)我想以某種方式提取屬性,例如src

str.dosmthg("src","http://stackoverflow.com/"); 

輸出:

"<iframe src="http://stackoverflow.com/" height="800" width="500"></iframe>" 

heightwidth相同的想法。

有什麼建議嗎?謝謝 !

+0

你可以簡單地使用JavaScript來實現你想要的。使用jquery可以很容易地完成。看看下面的鏈接http://www.w3schools.com/jquery/ –

+0

你可以在你的控制器中有單獨的變量,如果你在那裏建造它。然後在構建元素字符串時只需連接變量。這樣,如果你需要它們,你可以稍後獲得高度/寬度/等等。 –

回答

2

您應該創建一個臨時元素並將您的HTML放入其innerHTML。然後您將能夠操作子節點屬性。

var tempEl = document.createElement('div'); 
 
tempEl.innerHTML = '<iframe src="https://www.google.com/" height="800" width="500"></iframe>'; 
 
console.log(tempEl.childNodes[0].attributes['src'].value); 
 
tempEl.childNodes[0].attributes['src'].value = 'http://stackoverflow.com'; 
 
console.log(tempEl.childNodes[0].attributes['src'].value); 
 
console.log(tempEl.innerHTML);

2

可以使用瀏覽器來解析HTML,然後讀取從所得的DOM元素的屬性值;看評論:

// Your string 
 
var str = '<iframe src="https://www.google.com/" height="800" width="500"></iframe>'; 
 

 
// Create an appropriate parent element for the string; note we don't 
 
// actually attach this to the DOM anywhere 
 
var body = document.createElement('body'); 
 

 
// Use the element to parse the HTML 
 
body.innerHTML = str; 
 

 
// Get the iframe from the element 
 
var iframe = body.querySelector("iframe"); 
 

 
// Get the attributes from the element 
 
console.log("src = ", iframe.getAttribute("src")); 
 
console.log("height = ", iframe.getAttribute("height")); 
 
console.log("width = ", iframe.getAttribute("width"));

相關問題