Muzzlet
Muzzlet

Reputation: 239

How to add CSS style to HTML elements created with JavaScript?

I have created HTML elements with JavaScript to pull data from the back-end server. I am trying to add CSS style to the elements, but I am having trouble as to how.

I have tried using getElementById and setAttribute, but I'm keep getting an error. Whenever each item is pulled out from the back-end server, I want each information to be wrapped with a solid black border.

This is the code:

let div = "<div>";
        
        for (let i = 0; i < Items.length; i++) {

            div += "<h3>" + Items[i].title + "</h3><p><i><b> Posted: " + Items[i].time + "</b></i></p><p>" + Items[i].body + "</p>"

        }

        div += "</div>";

        $("#news-articles").html(div);

Upvotes: 1

Views: 2979

Answers (3)

Where is your CSS?

Just load a CSS file with styles for every element inside the #news-articles container:

#news-articles h3 {
/* rules */
}

#news-articles p {
/* rules */
}

etc...

I suggest you to wrap every news in a div for easily achieving what you pretend, which is adding a border to each of them.

for (let i = 0; i < Items.length; i++) {

            div += "<div class='container'><h3>" + Items[i].title + "</h3><p><i><b> Posted: " + Items[i].time + "</b></i></p><p>" + Items[i].body + "</p></div>"

        }

And then...

#news-articles .container {
    border: 1px solid #000;
}

Upvotes: 0

dev_event
dev_event

Reputation: 1

You complicate the code a lot. Just use list tags

    <ul>
    for (let i = 0; i < Items.length; i++) {
   <li>Coffee</li>....}
   ul li {
  background: #cce5ff;
  margin: 5px;
}

Upvotes: 0

T J
T J

Reputation: 43156

You can add class or style attributes while creating the HTML string like:

"<div class=\"red\" style=\"background: blue\">".

I recommend using single quotes or template literal so you wouldn't have to escape the nested double quotes:

'<div class="red" style="background: blue">'

const Items = [{
  title: 'hi',
  time: 2,
  body: 'hello'
}]

let div = "<div class=\"red\" style=\"background: blue\">";

for (let i = 0; i < Items.length; i++) {

  div += "<h3>" + Items[i].title + "</h3><p><i><b> Posted: " + Items[i].time + "</b></i></p><p>" + Items[i].body + "</p>"

}

div += "</div>";

$("#news-articles").html(div);
.red {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="news-articles"></div>

Upvotes: 1

Related Questions