Estoy tratando de crear esto en Javascript para poder insertarlo en el documento:
<div class="listing-small-badge award-badge" style=" vertical-align: top; position: relative; top: -250px; z-index: 2;"><i class="fa fa-tag award" style="background-color: #990000;"></i>Highest Rated</div>Y he intentado todo lo que se me ocurre, pero una vez que creo el elemento 'i', parece que no puedo agregarlo correctamente al elemento div.
Por ejemplo:
<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 class="test">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>Así es como puede agregar html dinámicamente usando js
//archivo js
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>No sé por qué jQuery sería necesario, pero esto es lo que funcionó:
jQuery(document).ready(function($){ var htmlData = '<div class="listing-small-badge award-badge" style="vertical-align: top; position: relative; top: -250px; z-index: 2;"><i class="fa fa-tag award" style="background-color: #990000;"></i>Highest Rated</div>'; $('body p').append(htmlData); });