1

I'm a new to coding and trying to wrap a large list of strings with HTML tags. After searching, I already found a method here but I've tried it in VS Code and it seems to be not working for me. Probably I'm doing something wrong.

To clarify it further, I'm trying to wrap a large list of strings with HTML tags.

Elina Arnwine
Freddie Cane
Melia Pittenger
Nobuko Grove
.....

to

<li class="nav-item"><a href="" class="nav-link text-small pb-0 ">Elina Arnwine</a></li>
....

Any assistance you can provide would be greatly appreciated.

3
  • 2
    Regex is completely wrong for this. Which language are you using? javascript? Commented Oct 3, 2019 at 20:57
  • 1
    yes javascript. Commented Oct 3, 2019 at 20:57
  • If I'm not using appropriate tags for the question, kindly please edit. Commented Oct 3, 2019 at 20:58

1 Answer 1

5

I think you're using javascript which makes it really simple to do this by mapping over the list and creating the elemnts:

const names = [
  'Elina Arnwine',
  'Freddie Cane',
  'Melia Pittenger',
  'Nobuko Grove'
  ];
  
function createLI(name) {
  const el = document.createElement('li');
  const a = document.createElement('a');
  el.className = 'nav-item';
  a.className = 'nav-link text-small pb-0';
  a.appendChild(document.createTextNode(name));
  el.appendChild(a);
  document.getElementById('ul').appendChild(el);
}

names.map(createLI);
<ul id='ul'></ul>

Or you could use a template

const names = [
  'Elina Arnwine',
  'Freddie Cane',
  'Melia Pittenger',
  'Nobuko Grove'
];
  

function manTemplate(name) {
  const tmp = document.getElementById('li-template');
  const clone = document.importNode(tmp.content, true);
  clone.querySelector('a').innerText = name;
  document.getElementById('ul').appendChild(clone);
}

names.map(manTemplate);
<template id="li-template">
    <li class="nav-item"><a href="" class="nav-link text-small pb-0 "></a></li>
</template>

<ul id='ul'></ul>

Sign up to request clarification or add additional context in comments.

1 Comment

You shouldn't be using map in these cases. map expects the function called to return something and then returns an array. You should be using forEach instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.