0

I have this JavaScript code that does createElement, but how can I style it from my separate CSS file?

JavaScript

emails.forEach(function(email) {
const element = document.createElement('div');
element.innerHTML = email.sender + ' ' + email.subject + ' ' + email.timestamp
document.querySelector('#email-container').append(element);
});

HTML

<div id="email-container">

</div>

CSS

#email-container .element{
    border-width:2px;
    border-style:solid;
    border-color:black;
}

1 Answer 1

1

if you're styling it that way, then you expect the div to have class element. So you just need one extra line to add that class to the element. Full code here:

emails.forEach(function(email) {
  const element = document.createElement('div');
  element.classList.add('element');
  element.innerHTML = email.sender + ' ' + email.subject + ' ' + email.timestamp
  document.querySelector('#email-container').append(element);
});
Sign up to request clarification or add additional context in comments.

3 Comments

I have added the line and edited the CSS to #email-container .element it does the work, do you suggest any other solution that is better used in real-world projects?
Not really, using a class seems fine - you usually use classes and/or IDs for CSS styles, and since you are adding several different elements here you can't use an ID (as they need to be unique in the document).
I see, Thank you!

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.