Convert dt/dd list into a li list using jquery?

I want to convert a list of product details from dt/dd html format into li?

for example:

<dt class="float-left"> Composition</dt>
<dd>Suede 100%</dd>
<dt class="float-left">Lining Composition</dt>
<dd>Suede 100%</dd>

into:

<li> Composition: Suede 100%</li>
<li> Lining Composition: Suede 100%</li>

I tried doing this numerous, but don’t know where to start?

Example fiddle: https://jsfiddle.net/nj0h4ddh/


solution

You could use the .wrapInner()/ .unwrap() methods:

Updated Example

$('.product-detail-dl').wrapInner('<ul></ul>')
  .find('ul').unwrap()
  .find('dt, dd').wrapInner('<li></li>')
  .find('li').unwrap();

Input:

<dl class="product-detail-dl">
  <dt class="float-left"> Composition</dt>
  <dd>Suede 100%</dd>
  <dt class="float-left">Lining Composition</dt>
  <dd>Suede 100%</dd>
</dl>

Output:

<ul>
  <li>Composition</li>
  <li>Suede 100%</li>
  <li>Lining Composition</li>
  <li>Suede 100%</li>
</ul>

In order to combine the dt/dd elements, you could use the following before wrapping/upwrapping the elements:

Updated Example

$('.product-detail-dl dd').each(function () {
  $(this).prev().append(': ' + this.innerText);
}).remove();

Input:

<dl class="product-detail-dl">
  <dt class="float-left"> Composition</dt>
  <dd>Suede 100%</dd>
  <dt class="float-left">Lining Composition</dt>
  <dd>Suede 100%</dd>
  <dt class="float-left">Sole Composition</dt>
  <dd>Rubber 100%</dd>
  <dt class="float-left">Brand Style ID</dt>
  <dd>333824045</dd>
</dl>

Output:

<ul>
  <li>Composition: Suede 100%</li>
  <li>Lining Composition: Suede 100%</li>
  <li>Sole Composition: Rubber 100%</li>
  <li>Brand Style ID: 333824045</li>
</ul>

As a side note, you could also use the .replaceWith() method for the same results:

$('.product-detail-dl dd').each(function () {
  $(this).prev().append(': ' + this.innerText);
}).remove();
$('.product-detail-dl').find('dt, dd').replaceWith(function () {
  return $('<li>' + this.innerHTML + '</li>');
});
$('.product-detail-dl').replaceWith(function () {
  return $('<ul>' + this.innerHTML + '</ul>');
});