Search code examples
jqueryhtmlarraysloopshref

Adding links for each genre through loops in jQuery


I have been trying to figure out d) and would really appreciate any help!

Below is the assignment. I have completed everything except for the last

"Using the starter code available in course content, add the following array:

var genres = ["Fiction", "Comedy", "Drama", "Horror", "Non-fiction", "Romance", "Satire"];

a) Create a element first and append to the body. Loop through the array, adding "li" elements to the "ul", with the each of the array items as the "li" content.

b) Instead of creating a list, make a table and put each array item in a "td" (table column)

c) Instead of columns, create table rows.

d) Outside of the loop used above, turn each word into a link, and link to a Wikipedia page for that word (target="_blank"). Note how Wikipedia structures their URL on the site."**

How would this be done?


Solution

  • Iterate over the array - create a str with each link and then pass it into the html to create a list of the wiki links. The has the added benefit of amending the DOM only once.

    Note the structure of the href for the wikipeadia page is "https://en.wikipedia.org/wiki/Fiction" so thats all you have to build in the string and substitute each item of the array at the end.

    var str='';
    
    var genres = ["Fiction", "Comedy", "Drama", "Horror", "Non-fiction", "Romance", "Satire"];
    
    genres.forEach(function(genre) {
     str += '<li><a href="https://en.wikipedia.org/wiki/'+genre+'">'+ genre + '</a></li>';
    })
    
    document.getElementById('wikiLinks').innerHTML = str;
    <ul id = 'wikiLinks'></ul>