Reputation: 22393
I have the following HTML to give ABC links for a long list of items divided into pages by letter of the alphabet. I cannot change the HTML.
<p>
<a href="A.html">A</a>
<!-- all the items on this page start with this letter
It is not contained in any special div, just floats among the links -->
B
<a href="c.html">C</a>
<a href="d.html">D</a>
<a href="e.html">E</a>
<a href="f.html">F</a>
<a href="g.html">G</a>
<!-- and so on through z -->
</p>
I need to put a separator (the following HTML) between every letter:
<span class="separator">|</span>
However, if I put a separator before or after every link, the plain letter will not have a separator between itself and one of the links surrounding it.
How can I place a separator between every link, without changing the HTML, keeping in mind that any of the letters can be plain text without a containing <a>
or any other tag except for the outer <p>
?
Edited to show desired results (two of many possibilities). The letter in bold is not a link; all the other letters are:
A | B | C | D | E | F ...
A | B | C | D | E | F ...
Upvotes: 4
Views: 672
Reputation: 78710
var separator = "<span class='separator'>|</span>";
$("p").contents().each(function(){
var $this = $(this);
if($.trim($this.text()).length>0){
if(this.nodeType == 3){
// text node, possibly multiple characters that need separation
var characters = this.nodeValue.replace(/\s/g, "").split("");
var output = "";
for(var i=0; i<characters.length; i++){
output += " " + characters[i] + separator;
}
$(this).replaceWith(output + " ");
} else {
$this.after(separator);
}
}
});
$(".separator:last").remove();
Upvotes: 2
Reputation: 324780
Try this:
var p = // some method of getting the correct <p> tag
var c = p.childNodes, i, isfirst = true, s;
for(i=0;i<c.length;i++) { // skip the first child node
if( c[i].tagName || c[i].nodeValue.match(/[a-z]/)) {
// if node is a tag or a non-empty text node
if( isfirst) isfirst = false; // skip first node
else {
s = p.insertBefore(document.createElement('span'),c[i]);
s.className = "separator";
s.appendChild(document.createTextNode("|"));
i++; // IMPORTANT! Adding a node requires us to manually iterate forward one step!
}
}
}
Upvotes: 2