I'm trying to create this in Javascript so that I can insert it into the document:
<div style=" vertical-align: top; position: relative; top: -250px; z-index: 2;"><i style="background-color: #990000;"></i>Highest Rated</div>
And I've tried everything I can think of, but once I create the 'i' element, I can't seem to properly append it to the div element.
For example:
<script type="text/javascript">
var div = document.createElement("div");
div.style.cssText = 'vertical-align:top; position: relative; top:-250px; z-index:2;';
div.classList.add("listing-small-badge");
div.classList.add("award-badge");
div.innerHTML = "Highest Rated"; //this works on its own, but disappears if/when I try to append the 'i' element/HTML tag
var i = document.createElement("i");
i.classList.add("fa");
i.classList.add("fa-tag");
i.classList.add("award");
//i.style.cssText("background-color: #990000;"); //doesn't like this for some reason TBD
//console.log(i); //prints out just fine
//div.innerHTML = i; //results in an empty div
//div.innerHTML = '<i >x</i>'; //results in an empty div
//div.insertAdjacentHTML("afterend", "<i class='test'></i>"); //results in "The element has no parent."
console.log(div);
</script>
CodePudding user response:
I'm at a loss as to why jQuery would be necessary, but here's what worked:
jQuery(document).ready(function($){
var htmlData = '<div style="vertical-align: top; position: relative; top: -250px; z-index: 2;"><i
style="background-color: #990000;"></i>Highest Rated</div>';
$('body p').append(htmlData);
});
CodePudding user response:
Here is how you can dynamically add html using js
//js file
function createElements() {
var div = document.createElement("div");
div.classList.add("listing-small-badge");
div.classList.add("award-badge");
div.innerHTML = "Highest Rated";
div.innerText='Dusting';
var i = document.createElement("i");
i.classList.add("fa");
i.classList.add("fa-tag");
i.classList.add("award");
i.href = 'google.com';
i.innerText = 'google';
div.appendChild(i);
const body = document.querySelector('body');
body.appendChild(div);
window.onload = (e)=>{
createElements();
}
}
//html
<body>
</body>
