0

is it possible to add an attribute to an element based on it's class name? For example, I have an input type checkbox like below

<input type="checkbox" class="ui-corner-all">

And I need to add an attribute called "tooltip" and a value for that tooltip if any element had the class name as "ui-corner-all". Which ultimately should become like

<input type="checkbox" tooltip="Corner All" class="ui-corner-all">

It is a dynamically generated element and I have no access to the HTML, need to do it via .ts file only. Any help on this? Thanks

1
  • Please explain your issue, instead of asking about what you think is the solution. What's the request behind this ? Commented Oct 10, 2022 at 11:29

1 Answer 1

1

hmm, if you don't have an access to the HTML, it becomes a little bit difficult and ugly :(.

Here is the workaround in typescript(But please if you can avoid of doing this will be much better):

put the HTML in the wrapper div

<div #pureHTMLRef> 
   <!-- your HTML piece goes here -->
</div

Component

export class Component implements AfterViewInit {
  
  @ViewChild('pureHTMLRef') htmlContainer: ElementRef<HTMLElement>;

  ngAfterViewInit() {
     this.addTooltipToUIElements();
  }

  addTooltipToUIElements() {
      const container = htmlContainer.nativeElement;
      const uiElement = container.querySelectorAll('[class~=ui-]'); // select all elements that is containing `ui-`
      uiElement.forEach(element => {
        const class = [...element.classList].find(class => class.includes('ui-', 0));
        if(!class) { return; }
        const name = class.replace('ui-', '').replace('-', ' ');
        element.setAttribute('tooltip', this.toTitleCase(name));
      })

  }

  toTitleCase(str) {
   return str.replace(
     /\w\S*/g,
     function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
     }
  );

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.