How to only modify "text" while modifying the dom using javascript
I'm trying to write an "unbreakabl开发者_运维技巧e" class using jQuery, so that:
<span class=unbreakable>
some text in here
maybe with a <span title="tag">tag</span> or something
</span>
would have each space replaced with
. The problem is, if I do something like
$(".unbreakable").html
( replaceAll($(".unbreakable").html(), " ", " ")
);
It'll replace the spaces in tags as well - no good. So I'm looking for a way to avoid the tags without writing an html parser myself. Anyone know a good way to do this?
Wouldn't adding:
.unbreakable {
white-space: pre;
}
… to your stylesheet be easier?
Good direction with the CSS. How about nowrap?
.unbreakable { white-space: nowrap; }
[edit] fixed in response to a comment. This is probably not IE-compatible; haven't tested on anything other than Firefox. C.f. How do I select text nodes with jQuery.
<script language="JavaScript" type="text/javascript" src="jquery.js" ></script>
<link rel="stylesheet" href="styledButton.css" type="text/css" >
<script type="text/javascript">
$(document).ready(function () {
var NBSP = '\u00a0';
$(".unbreakable").css("border", "solid red 1px").contents().each(function(x){
if (this.nodeType == Node.TEXT_NODE) {
this.nodeValue = this.nodeValue.replace(/ /g, NBSP);
}
});
} );
</script>
</head>
<body>
<div id="log" style="width: 10px">
<span class="unbreakable">testing <span title="Moo">XXX YYY</span> testing 1 2 3</span>
<span class="breakable">(Now this is a breakable span)</span>
<span class="unbreakable">testing again...</span>
</div>
<div id="A"></div>
</body>
精彩评论