Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <p>I need to replace the space between the 2 words with a BR tag - I've tried quite a few things, this one I thought would work, but the original script only does it to the first item :( </p>
  
  <p>I modified this - <a href="http://stackoverflow.com/questions/10870888/javascript-how-to-replace-white-spaces-which-are-not-in-html-tags">http://stackoverflow.com/questions/10870888/javascript-how-to-replace-white-spaces-which-are-not-in-html-tags</a></p>
  
<span class="navtext">Lorem ipsum</span>
  
<br>
    
<span class="navtext">Lorem ipsum</span>
    
<br>
    
<span class="navtext">Lorem ipsum</span>
</body>
</html>
 
// Doesnt work
// var span = document.getElementsByTagName(".navtext");
// Only works for the first one
var span = document.querySelector(".navtext");
// Doesnt work
// var span = document.querySelectorAll("navtext");
function space() {
    var elem = document.createElement("br");
    // elem.className = "space";
    // elem.textContent = " ";
    return elem;
}
function replace(elem) {
    for(var i = 0; i < elem.childNodes.length; i++) {
        var node = elem.childNodes[i];
        if(node.nodeType === 1) {
            replace(node);
        } else {
            var current = node;
            var pos;
            while(~(pos = current.nodeValue.indexOf(" "))) {
                var next = current.splitText(pos + 1);
                current.nodeValue = current.nodeValue.slice(0, -1);
                current.parentNode.insertBefore(space(), next);
                current = next;
                i += 2;
            }
        }
    }
}
replace(span);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers