Reputation: 11
I'm a newbie and am having a hard time with some text that has no element, I am trying to wrap text outside of a tag with a list tag :
http://jsfiddle.net/danb/7xu6A/
HTML
<ul>
<li><a href="#">item1</a></li>
<li><a href="#">item2</a></li>
<li><a href="#">item3</a></li>
text <br>to wrap and combine
<li><a href="#">item4</a></li>
</ul>
This was working for me until I came across some instances where the string was broken with a
tag - even if i take out the <br>
first they are still separate nodes and get wrapped as such.
$('ul').contents().remove('br')
.filter(function()
{
return (this.nodeType === 3 && $.trim(this.data) !== '');
}).wrap('<li class="nav current"></li>');
any help is greatly appreciated
Upvotes: 0
Views: 484
Reputation: 1514
Here is your solution (assume your ul has an id of "whatever" in this example)
Your final wrapped text is stored in the variable 'finaltext'
NOTE: Uncommenting the commented lines will also remove the text "text to wrap and combine" from your page, and then also append "text to wrap and combine" as a new list item, and finally, take out the br tag!
var d = document.getElementById("whatever");
var nds = d.childNodes;
var finaltext = "";
$(nds).each(function(){
var trmdvl = $.trim(this.nodeValue);
if(trmdvl){
finaltext += trmdvl + " ";
//$(this).remove();
}
});
//$(d).append("<li>" + $.trim(finaltext) + "</li>");
//$('br').remove();
Assumed HTML Below:
<ul id="whatever">
<li><a href="#">item1</a></li>
<li><a href="#">item2</a></li>
<li><a href="#">item3</a></li>
text <br>to wrap and combine
<li><a href="#">item4</a></li>
</ul>
Upvotes: 1