Search code examples
javascripthtml

How to Wrap Multiple HTML Strings with Tags?


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.


Solution

  • 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>