Lukas Lukas - 12 days ago 4
HTML Question

Add html content to js generated class

I have a trivial issue and need your help. Thanks to you, I have 2690 squares generated by js:

var i, square, text, container = document.getElementById("square_container");
for (i = 1; i <= 2690; i += 1) {
square = document.createElement("div");
square.id = "square" + i;
square.classList.add("square");
text = document.createElement("h1");
text.innerHTML = i;
text.id = "text" + i;
square.appendChild(text);
container.appendChild(square);
text.classList.add("hover");
}


The code above generate 2690 of this:

<div id="square1" class="square"><h1 id="text1">1</h1></div>


And now, I need to add following html content to each .square class:

<div class="hover"><a href="#">Click Me</a></div>


So in the result I need to have:

<div id="square1" class="square"><h1 id="text1">1</h1>

<div class="hover"><a href="#">Click Me</a>

</div>
</div>


https://fiddle.jshell.net/tynw5c34/3/

I tried .append, .addClass...but it doesn't work. Thank you in advance for your help!

Answer

Lukas. To achieve the function you were looking for using jQuery, I added an external resource:

https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js

and added this to the javascript:

$( ".square" ).append("<div class=\"hover\"><a href=\"#\">Click Me</a></div>")

I hope this helps.

Comments