0
let example  = document.createElement("p");

and now I want to add a new class to the p (<p>) that I just created.

3
  • example.classList.add("myClass"); Commented Jun 24, 2021 at 19:09
  • example.id="myID"; Commented Jun 24, 2021 at 19:09
  • ...or example.className = "anyClass" Commented Jun 24, 2021 at 19:10

2 Answers 2

1

Use the classList and id properties of the element.

let example  = document.createElement("p");
example.id = "newid";
example.classList.add("newclass");
Sign up to request clarification or add additional context in comments.

Comments

0

You can try it this way:

// create node
const node = document.createElement('p');
// add id
node.setAttribute('id','new_id');
// add class
node.setAttribute('class', 'new-class');

3 Comments

did you mean node.setAttribute?
Thanks @AmirShiffer. I've edited the answer now. Accept it if this suits your requirement.
great, thanks you’ve helped me a lot