1

Link to CodePen.

I'm trying to wrap all city texts under the Location column, with a link to their specific location page on a website. So Cambridge would be wrapped in a link tag going to the Cambridge page, Timmins would be wrapped in a link tag going to the Timmins page, etc.

I've started off with just two links to try and get this working. Looping through the td's within the location column, and if the value equals specific text, add a link to it. Trying to get it to work.

JS

/////// Grab the Locations column ///////

let col5 = document.querySelectorAll("td:nth-child(5)");

// Cities Data

const cities = [
  {
    id: 1,
    city: 'Cambridge',
    link: '/locations/cambridge'
  },
  {
    id: 2,
    city: 'Timmins',
    link: '/locations/timmins'
  }
]

/////// Link up all td's to location pages ///////

// Loop over locations column
for (let i = 0; i < col5.length; i++) {
  // If it matches the specific city, wrap text around link tag linking to specific location
  if (col5.innerHTML === cities[0].city) {
    // Set Links Info
    a.setAttribute("href", cities[0].link);
    // Append
    col5[i].appendChild(a);
  } else if (col5.innerHTML === cities[1].city) {
    // Set Links Info
    a.setAttribute("href", cities[1].link);
    // Append
    col5[i].appendChild(a);
  }
}
JD Fill
  • 392
  • 2
  • 7
  • 24
  • You should try and add a [mcve] example to your question rather than link to a codepen. It will help you narrow down the problem, and help us out too. – Andy Mar 17 '20 at 14:42

1 Answers1

1

As you might imagine, copying/pasting/modifying the code for each of the cities is not ideal in any way.

You could consider using array methods such as forEach and find...

const cities = [
  { id: 1, city: 'Cambridge', link: '/locations/cambridge' },
  { id: 2, city: 'Timmins', link: '/locations/timmins' }
]

// Go through each cell
let col5 = document.querySelectorAll("td:nth-child(5)");
col5.forEach(function(el) {
  // Find the city
  var city = cities.find(function(x) { return x.city == el.innerHTML; });
  if (city) {
    // Wrap in a link
    el.innerHTML = '<a href="' + city.link + '">' + el.innerHTML + '</a>';
  }
});
<table>
  <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>Cambridge</td></tr>
  <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>Timmins</td></tr>
</table>

(Minor note before anybody comments... I'm using function(x) {} instead of x => because I still have to code for IE11, which doesn't support arrow functions)

freefaller
  • 19,368
  • 7
  • 57
  • 87
  • Thank you so much! I agree, this code is way less verbose. – JD Fill Mar 17 '20 at 15:02
  • You're welcome - good luck with the rest of your project. I notice you're using jQuery in your codepen, so the code could probably continue to be improved... but as you haven't stated it in your question or tag, I've not gone that route – freefaller Mar 17 '20 at 15:04