除非我犯了错误,否则我没有找到解决问题的干净/简单的答案。
我在字符串中有一个标签并包含 src 属性:
var str = "<iframe src="https://www.google.com/" height="800" width="500"></iframe>"
使用 JS 或 AngularJS(仅!)我想以某种方式提取属性,例如 src
:
str.dosmthg("src","http://stackoverflow.com/");
输出:
"<iframe src="http://stackoverflow.com/" height="800" width="500"></iframe>"
与高度
和宽度
相同的想法。
有什么建议吗?谢谢!
最佳答案
您应该创建一个临时元素并将 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);
关于javascript - 如何使用 javascript 或 angularjs 从 html 标签中提取/编辑属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705628/