1

I'm trying to pass an array and return a list of links from the values in the array.

This is what I want in the end from

var list = ["Link 1", "Link 2", "Link 3"]

I've tried a few different ways and I'm getting different errors. I was hoping someone could point me in the right direction or point out where my issue is.


  var list = document.createElement('ul').attr("id", "ticketList"); // Create the list element

  $.each(arr, function(i, arr) {
    $("#ticketList").append("<li><a href="'https://jeng.internal.com/browse/'+arr[i]+'"  id="'+arr[i]+'_link">'+arr[i]+'</a></li>");

    return list;
  }

I get the error

Uncaught ReferenceError: onSearchClickHandler is not defined

I've also tried:

function makeUL(arr) {  

  var list = document.createElement('ul'); // Create the list element

  for (var i = 0; i < arr.length; i++) { //loop through the array to make the list
        var z = document.createElement('li');
        var item = '<a href="https://jeng.internal.com/browse/'+arr[i]+'"  id="'+arr[i]+'_link">'+arr[i]+'</a>';
        z.appendChild(item)
        list.appendChild(z); // Add it to the list
    }
    return list;
  }

From this I get the error

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

I looked around and based off this question and answer I tried adding in .innerHTML, but it takes me back to the same error originally Uncaught ReferenceError

Any help would be much appreciated.

pcdr
  • 183
  • 2
  • 12

1 Answers1

1

To achieve expected result, make below changes to your code

  1. Create ul element and append to body

    var list = document.createElement('ul'); // Create the list element $("body").append(list)

  2. Then add attribute id -ticketList

    $('ul').attr("id", "ticketList");

  3. Loop arr using $.each

working code for reference

var arr = ["Link 1", "Link 2", "Link 3"]

var list = document.createElement('ul'); // Create the list element
$("body").append(list)
$('ul').attr("id", "ticketList");
  $.each(arr, function(i, arr) {
    $("#ticketList").append("<li><a href='https://jeng.internal.com/browse/"+arr+"'  id="+arr+"_link>"+arr+"</a></li>");
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

codepen - https://codepen.io/nagasai/pen/LYPJoaN?editors=1010

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40