I am trying to add my element to the unordered list. But during the creation of the element I also want to link this to an external css file which has the css property.
My HTML file: index.html
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1 id="header">Last King</h1>
<h2>Buy Groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em>figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic sugar</li>
</ul>
<script src="index.js">
</script>
</body>
</html>
My CSS File: index.css
.myclass {
color: brown;
text-emphasis-color:blue;
}
My JS File: index.js
let a = document.getElementsByTagName('ul')[0];
let myelement = document.createElement('li');
// tried this first
myelement.style.border = '2px solid red';
myelement.style.backgroundColor = 'rgb(255, 125, 115)';
let mytext = document.createTextNode('Green Onions');
// second method I tried to link with the external CSS file which I actually want
myelement.setAttribute("class","myclass")
// third method I tried to link with the external CSS file which I actually want
let myattrib = document.createAttribute('class');
myattrib.value = "myclass"
myelement.setAttributeNode(myattrib)
a.appendChild(mytext)
None of these methods works in adding a new element with a CSS property, although with the first method I am able to just add the text node Green Onions
.
I am learning JS for the first time.
Can someone provide me with information on what I am doing wrong?
I have referred following solutions.
Add CSS attributes to element with JavaScript