How can I use jQuery to separate multiple words in a td
with an HTML tag such as <br/>
?
For example, <td>hello bye</td>
would become <td>hello <br/> bye</td>
.
How can I use jQuery to separate multiple words in a td
with an HTML tag such as <br/>
?
For example, <td>hello bye</td>
would become <td>hello <br/> bye</td>
.
With jQuery 1.4+ you could do this:
$('td').html(function(i,html){
return html.replace(/\s/g, '<br>');
})
The above doesn't appear to be working, where as changing the .html
to .text
works, but of course you can't add HTML elements that way. So your best bet would be to do this (change your TD Id's to TD classes):
Edit #2 (replace the bad code)
$(document).ready(function(){
$('td.myTd').each(function(){
$(this).html( $(this).html().replace(/\s/g, '<br>') );
})
})
But as Max Shawabkeh pointed out, this will cause problems if you have any HTML with attributes inside of the <td>
(e.g. <span class="text">...</span>
)
This will work only if the HTML in the td
's does NOT contain any tags.
$("td").each(function(){
this.innerHTML = this.innerHTML.replace(/ +/g,"<br/>");
});