I am new to Java script and in an assignment I am directed to create 2 JS
files and then display data dynamically in HTML. One JS file data.js
file have an array of objects
(lets say table of items) and another JS file has function which loads those items
, create HTML elements and display items (catalog) on HTML page.
I have found relevant post [here](How do I include a JavaScript file in another JavaScript file? cript-file-in-another-java script-file) . But I am still unable to understand that how to access display data from 1 JS file
while loadfunction()
is located into another JS file.
Also I don't know how to assign an External CSS class to this dynamically created element.In boutique.js the syntax is
itemName.classList.add("addCSS");` Please help me in this regard. Thank you.
> data.js
var catalog = [
{
code: 100,
name: "Learn JS",
desc: "To make your web paged dynamic",
price: 150,
image: "/images/100Tshirt.jpg"
},
{
code:101 ,
name: "T Shirt",
desc: "Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.",
price: ,
image: "/images/101Tshirt.jpg"
},
{
code:102 ,
name: "T Shirt",
desc: "Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.",
price: ,
image: "/images/102Tshirt.jpg"
}
// {
// name: "Meowsalot",
// species: "Cat",
// favFoods: ["tuna", "catnip", "celery"],
// birthYear: 2012,
// photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
//
];
> boutique.js
function chargerArticles
{
var items= document.getElementsById('content')
for (var i = catalog.length - 1; i >= 0; i--) {
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
// div.innerHTML = "Hello";
var itemName = document.createElement("h2");
itemName.classList.add("addCSS"); //also hoow to acess style.css to style h2 (dynamic element)
}
}
/*style.css*/
.addClass
{
font-size: 44px;
color:red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/data.js"></script>
<script src="js/codeboutique.js"></script>
</head>
<body onload="chargerArticles()">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<section id="content" >
</section>
</body>
</html>