Emidomh Emidomh - 4 months ago 13
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
<iframe>
tag with
<button>
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

etc....

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

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


But I don't know how to specify this for
<iframe>
tags

Any suggestion ? Thanks !




EDIT :

Here a new example, what I want to do :

In
var str
I have 2
<iframe>
tags with different
src
attribute value :

the first iframe has
src='urlAAA'

the second
src='urlBBB'


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) {
array.push(ctl.outerHTML)
});
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

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();
    }