2016-06-08 42 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"));

相关问题