Jeff E Jeff E - 4 months ago 9
HTML Question

Formatting a href link with appendChild, setAttribute, etc

I am attempting to populate a list with href links via javascript.

Here is an example of the html I would like to create:

<li> <a href="#modal-one">Complete blood count</a></li>


Where "#modal-one" displays a pop up.

I have used the following and several other iterations to try and create this dynamically:

<script>
var listItem = [];
function createTestList() {

var tests = results.tests; //an array to tests to populate list
var i;
var j;

for (i = 0; i < tests.length ; i++ ){

listItem[i] = document.createElement("li");
var node = document.createTextNode(tests[i].name);
listItem[i].appendChild(node);
listItem[i].setAttribute("href", "#modal-one");
addOnClick(i);
//var element = document.getElementById("div1");
//element.appendChild(listItem[i]);

document.body.appendChild(listItem[i]);
console.log(listItem[i]);
};
};
function addOnClick(j) { //this is separate to handle the closure issue

listItem[j].onclick = function() {loadModal(j)};
};
</script>


However, this code (and several others) produce:

<li href='#modal-one'>Complete Blood Count</li> //note missing <a>...</a>


It appears there are several ways to achieve this, but nothing seems to work for me...

Answer

You are never actually adding in an anchor tag. You are creating a list-item (li), but you are adding an href to that list-item rather than adding an anchor node to it with that href. As such, the browser just thinks you have a list-item with an href attribute.

Consider using the following instead:

<script>
var listItem = [];
    function createTestList() {

        var tests = results.tests;  //an array to tests to populate list
        var i;
        var j; // Never actually used in function. Consider omitting

        for (i = 0; i < tests.length ; i++ ){ 

            // create the list item
            listItem[i] = document.createElement("li");

            // Create the anchor with text
            var anchor = document.createElement("a");
            var node = document.createTextNode(tests[i].name);
            anchor.appendChild(node);
            anchor.setAttribute("href", "#modal-one");

            // Set the onclick action
            addOnClick(i, anchor);

            // Add the anchor to the page
            listItem[i].appendChild(anchor);

            document.body.appendChild(listItem[i]);
            console.log(listItem[i]);
        };
};

// Modified "addOnClick" to include the anchor that needs the onclick
function addOnClick(j, anch) {  //this is separate to handle the closure issue

     anch.onclick =  function() {loadModal(j)};
};
</script> 

A couple things to note:

  1. I have modified your addOnClick() function because it is the anchor element that needs the onclick, not the list item.
  2. I have added in the creation of an anchor element rather than simply creating a list item and adding the href to that.