views:

210

answers:

3

I'm trying to write an "unbreakable" 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 &nbsp;. The problem is, if I do something like

$(".unbreakable").html
(   replaceAll($(".unbreakable").html(), " ", "&nbsp;")
);

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?

+6  A: 

Wouldn't adding:

.unbreakable {
    white-space: pre;
}

… to your stylesheet be easier?

David Dorward
+1, and note: if you don't want all of the behaviors of pre-formatted whitespace (new lines in text treated as line breaks rather than spaces), you can safely use the CSS rule in conjunction with `$('.unbreakable').html($('.unbreakable').html().replace(/\r?\n|\r/g, ' '));`
eyelidlessness
Yes it would be easier. I'm gonna go with Jeff Meatball's nowrap (didn't know that existed actually). It looks like it works more like I expect.
B T
Just to let you know also, pre doesn't work in IE. Damn microsoft to hell. +1 btw.
B T
A: 

[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>
Nickolay
http://jsbin.com/iqese
Mark
Thanks for all the effort, but it doesn't work. I tried<span class="unbreakable">testing <span title="Moo">yeah</span> testing 1 2 3</span>and the title didn't work (indicating its replacing spaces in the inner tags)
B T
gah, sorry, careless reading on my part. In any case the CSS solution is better if it suits you, I was just practicing in jQuery :)
Nickolay
+3  A: 

Good direction with the CSS. How about nowrap?

.unbreakable { white-space: nowrap; }
Jeff Meatball Yang
Great solution. Didn't know white-space existed. I still would love to see a way to avoid tags like i was looking for.. I'm sure i'll run across the need some day. Thanks!
B T