How do I add an id to a new element in JavaScript?

  • 0
    How do I add an id for a new Img element?

    Let's say we create a new IMG element with the 'comment__img' class and I want to add an id = '' attribute to this element. To add a link to a picture for this element in the future.
    let newCommentHeader = document.createElement('div');
    let newCommentImg = document.createElement('img');
    
      newCommentHeader.append(newCommentImg);
      newCommentImg.classList.add('comment__img');
    JavaScript Anonymous, Aug 27, 2020

  • 2 Answers
  • 0
    newCommentImg.setAttribure ('id', 'new_ go');

    UPD: Well, a typo)) You should write setAttribute
    Anonymous

  • 0
    Better to work with DOM properties:

    newCommentImg.id = 'id';
    Thomas Reilly

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!