skip to Main Content

I am trying to assign element’s attributes in typescript using setAttribute like this w3school example

Here is my JavaScript:

const p = document.createElement('p');
p.setAttribute('class', 'demoClass');
p.innerText = 'Hello';

and .css:

.demoClass {
  background-color: #00ffff !important;  
}

But this way it doesn’t take the style.
The only solution I’ve found is the following:

p.setAttribute('style', 'background-color: #00ffff !important');

Does anyone know how I can give the style using the class and not directly assigning it? Thank you in advance.

Update:

This code works fine as typescript, see here: here
But not in an angular project, see here

2

Answers


  1. You should use classList, not setAttribute:

    const p = document.createElement('p');
    p.classList.add("your-class");
    // do whatever you need with the new p
    

    Replace the your-class with the class that you need to add.

    Login or Signup to reply.
  2. Your app component does not load at all, here is a project I setuped to make it work: here

    so i had to use AfterViewInit, so I can get the element by id, ngOnInit is not a good approach, bcs nothing is loaded yet.

    Also you must use ViewEncapsulation.None, The reason lies in how Angular’s ViewEncapsulation works. By default, Angular scopes component styles to ensure that they do not "leak" into other components or the global DOM. Another approach is to use global CSS within file styles.css then you do not need to set ViewEncapsulation to none

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search