Search code examples
javascripthtmlangulartypescriptrenderer

Unable to modify innerHTML for anchor element


I'm trying to add some styles by DOM manipulation using angular renderer2.

I could updated styles for all html elements expect for anchor.

In the below e.g, I'm trying to replace this text www.url.com with this World to an anchor link.

Note: Only trying to change the text, not the href

  styleList = [
    {
      ori: 'www.url.com',
      replace: 'World'
    }
  ];

When I inspect <a href="wWorld">www.url.com</a>, replace text is getting added to the href.

So expected output should be <a href="wwww.url.com">World</a>

Why this is happening only to anchor tag ?

Below is the function, which will update the DOM

styleList.forEach(styleItem => {
  for (const childNode of childNodes) {
    renderer.setProperty(childNode, 'innerHTML', childNode.innerHTML.replace(styleItem.ori, styleItem.replace));
  }
});

You can check this stackblitz link for reference.

Please help.


Solution

  • Here is what I've achieved https://stackblitz.com/edit/angular-mdhle9?file=src/app/style.service.ts

    The main thing I did is changed your service to use RegExp groups

    for (const childNode of childNodes) {
       const regex = new RegExp('<(.*)>' + styleItem.ori + '<(.*)>')
    
       renderer.setProperty(childNode, 'innerHTML', childNode.innerHTML.replace(regex, '<$1>' + styleItem.replace + '<$2>'));
    }
    

    Here I create two matching groups which will copy the innner of HTML opening and closing tag.

    And then I simply return these groups(tags inner) back to < > and place the value between them.