appu appu - 5 months ago 22
Javascript Question

InnerHTML does not outputs anchor elements but instead outputs current pg url. why?

In the following code,

links_container.innerHTML = links;
instead of
<a href='#'>Page 1</a>


<div class="pagination-links"></div>


function createLinks() {
var links_container = document.getElementsByClassName('pagination-links')[0];

for(i=1; i<=5; i++){
var link = document.createElement('a');
var txt = document.createTextNode('Page ' + i + " ");
link.setAttribute("href", "#");
links_container.innerHTML = link;

Can anybuddy explain. why

Answer Source

innerHTML is a string property and thus takes a string as value. Your link is an element object and because of this it's implicitly converted to a string with its toString() method, which does indeed return the URL.

Here are two ways you can fix this:

Both of these solutions require you to clear the container before the for loop by running links_container.innerHTML = ''

  1. Append the element with links_container.appendChild(link)

  2. Use the outerHTML of the element object: links_container.innerHTML += link.outerHTML

The first option is the more appropriate one as it inserts the DOM element you created into the DOM directly. The second option converts your DOM element to a string and then forces the browser to create a new DOM element from that HTML. If there had been any event listeners added to the element they would've been lost.