Trying to wrap all words prior to the "," in each td cell. Note that words prior to "," in each cell will be different , so can not target a specific word per say...
Existing html
<td class="name">
<a href="" title="" class="">lastName, firstName</a>
</td>
Desired outcome
<td class="name">
<a href="" title="" class=""><span>lastName</span>, firstName</a>
</td>
Attempts , all of which destroy the a href structure , i need to keep the a tag with class,title and href as is and just wrap the word/words prior to ","
$('td.name').each(function() {
$(this).html($(this).text().replace(/,.*$/, '<span >$&</span>'));
});
$('td.name').html(function(i, v) {
return v.replace(/([^,] )(,)/, '$1<span >$2</span>$3');
});
$('td.name').html(function (i, html) {
return html.replace(/(.*?,)/, '<span>$1</span>')
});
CodePudding user response:
You can create a TreeWalker for each <td>
and use it to find all the text nodes, passing in a filter to locate only the ones containing commas.
From there, you can split the text into chunks and map each pre-comma chunk to a new <span>
then replace the entire text node with the new set of nodes.
const createSpan = textContent => Object.assign(
document.createElement("span"),
{ textContent }
)
const filter = {
acceptNode: node =>
node.data.includes(",") ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
}
document.querySelectorAll("td.name").forEach(td => {
const treeWalker = document.createTreeWalker(
td,
NodeFilter.SHOW_TEXT, // select only text nodes
filter, // filter for content with commas
false
)
let node
while (node = treeWalker.nextNode()) {
// split the text on comma, keeping the delimiter
const chunks = node.data.split(/(?=,)/)
// keep the last chunk as-is
const last = chunks.pop()
// replace the text node with the new node set
node.replaceWith(...chunks.map(createSpan), last)
}
})
span { color: red; }
<table border="1">
<tr>
<td class="name">
<a href="" title="" class="">lastName, firstName</a>
</td>
</tr>
<tr>
<td class="name">
<a href="" title="" class="">no commas</a>
</td>
</tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I really didn't see any use for jQuery here.