Emidomh Emidomh - 1 year ago 83
HTML Question

Replace html tag attribute in a string using AngularJS

I have a string containing html tags :

var str = "<div><p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src='urlAAA' height='400' width='800'></iframe><p></p><p><sub>hello blabla</sub></p><p><br></p><iframe src='urlBBB' height='400' width='800'></iframe></div>";

I want to replace each
tag with
tag in this way:

"<button type="button">Click Me for iframe n°1 !</button>"
for first iframe

"<button type="button">Click Me for iframe n°2 !</button>"
for second iframe


I'm using angularJS. I think the solution is to do something like this :

var ele = angular.element(str);
return "<button type='button'>Click Me for iframe n°" + index + " !</button>";

But I don't know how to specify this for

Any suggestion ? Thanks !


Here a new example, what I want to do :

var str
I have 2
tags with different
attribute value :

the first iframe has

the second

I want to get access to the src attribute and replace it with an another url.

function editFrameAttributes(str){
var array =[];
var eles= angular.element(str).find('iframe');
[].forEach.call(eles, function (ctl) {
Object.keys(array).forEach(function (key) {
var tempEl = document.createElement('div');
tempEl.innerHTML = array[key];

tempEl.childNodes[0].attributes['src'].value = "www.something.com";
tempEl.childNodes[0].attributes['width'].value = '1234';

array[key] = tempEl.innerHTML;
//then I don't know how to replace old iframes by new iframes in 'str'

return newStr;

The output should look like this :

var str = "<div><p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><div><iframe src='www.something.com' height='400' width='1234'></iframe></div><p></p><p><sub>hello blabla</sub></p><p><br></p><div><iframe src='www.something.com' height='400' width='1234'></iframe></div></div>";

Answer Source

Finally, here the solution I found myself :

function editFrameAttributes(str,newSrc){
      var eles = angular.element("<div>"+str+"</div>");
      eles.find('[src]').each(function() {
        this.src = newSrc;
      return eles.html();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download