Javascript: how to get text nodes following/preceding break tags and wrap them with ddb tag?
I have accomplished 开发者_JS百科this in Jquery but would like an implementation in Javascript without dependence on any libraries.
$("br",document).parent().contents().each(function() {
var text = this.textContent ? this.textContent : this.innerText;
text = this.textContent.replace(/\s+/g, '')
if ( this.nodeType == 3 && text.length != 0) {
$(this).wrap('<ddb></ddb>')
}
});
The following code should do the exact same thing as your function does.
<html>
<body>
Hello
<p>
Hello
<br/>
Hello 2
<br/>
<br/>
<br/>
</p>
<button onclick="wrapText()">Wrap</button>
<script type="text/javascript">
function wrapText() {
var nodeList = document.getElementsByTagName('br');
for (var i=0; i < nodeList.length; i++) {
var node = nodeList[i];
var parentNode = node.parentNode;
if (!parentNode) continue;
for (var c=0; c < parentNode.childNodes.length; c++) {
var child = parentNode.childNodes[c];
if (child.nodeType != 3) continue;
if (child.nodeValue.match(/[^\s]/) != null) {
var newElement = document.createElement("b");
newElement.innerHTML = child.nodeValue;
parentNode.insertBefore(newElement, child);
parentNode.removeChild(child);
}
}
}
}
</script>
</body>
</html>
However, I should point out that if the <br/>
is wrapped in any element, you are only getting the childNodes of that element, so if it was a simple <b>
tag you would only wrap text nodes inside the <b>
with <ddb></ddb>
(what is that, by the way?).
You also had a bug that you were assigning text
to node.textContent ? node.textContent : node.innerText
but then the next line simply used node.textContent
, so I fixed that. I also changed the regex to simply match the first non-whitespace character, and if it did find one, it wrapped it.
精彩评论