I was able to turn a long string into a dl list as shown below:
<div class="classA">
<dl id="idA"> Display # 252215425: </dl>
<dl id="idB">3 Apples </dl>
<dl id="idC">3 Peaches </dl>
<dl id="idD">10 Seadless Watermelons </dl>
<dl id="idE">23 Bananas </dl>
</div>
The result I want is:
<div class="classA">
<dl id="idA">
<dd>252215425</dd>
<dt>Display #</dt>
</dl>
<dl id="idB">
<dd>3</dd>
<dt>Apples</dt>
</dl>
<dl id="idC">
<dd>3</dd>
<dt>Peaches</dt>
</dl>
<dl id="idD">
<dd>10</dd>
<dt>Seadless Watermelons</dt>
</dl>
<dl id="idE">
<dd>23</dd>
<dt>Bananas</dt>
</dl>
</div>
The goal I am trying to achieve:
1. split each dl content into an array
2. find numbers and save them in “n”
3. find text and save them in “w”
4. wrap “n” with ‘dd’ tag
5. wrap “w” with ‘dt’ tag
6. the “n” & “w” should NOT have leading & trailing white spaces
Here is the code I came up, but it didn’t work…
$("div.classA dl").each(function(){
var a = $("div.classA dl").html();
a = a.split(' ');
var n = a.match(/d+/);
var w = a.match(/D+/);
$("div.classA dl").text('');
$("div.classA dl").append('<dd>'n'</dd>');
$("div.classA dl").append('<dt>'w'</dt>');
});
That’s pretty much it, but you have a couple of small issues in your code:
\dinstead of justd. Same goes withD, where it should be\D;matchreturns an array, thus you need to access the first position of it to obtain the matched value;$.eachalready iterates over alldls, no need to select them all again in each iteration of the loop. Just refer to the element that is being iterated, usingthis.Here’s the fixed code and a DEMO: