jQuery Text Replace
What is the jQuery equivalent to only replacing the text node, not the entire contents of a DOM element?
HTML
<a href="#" class="button"><span class="icon"></span>Before Text</a>
<br />
<button value="jquery-replace">Use jQuery to replace text</button>
<button value="reset">Reset</button>
<button value="javascript-replace">Use Javascript to replace text</button>
CSS
.button {
display: inline-block;
padding: 4px 6px;
border: 1px solid grey;
text-decoration: none;
margin: 10px;
box-shadow: 0 0 2px #C0C0C0 inset, 1 1px 2px #888888;
border-radius: 4px;
text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
vertical-align: top;
}
.button .icon {
width: 17px;
height: 17px;
display: inline-block;
margin-right: 6px;
background: url('http://nicolas.kruchten.com/content/wp-content/uploads/2011/04/icon-stackoverflow.png') no-repeat;
vertical-align: top;
}
JavaScript
$(document).ready(function() {
$('button').click(function() {
var type = $(this).val(),
$button = $('a.button');
switch (type) {
case 'reset':
$button.html('<span class="icon"></span>Before Text');
break;
case 'jquery-replace':
$button.text('jQuery Text');
break;
case 'javascript-replace':
$button[0].lastChild.replaceWholeText('Javascript Text');
break;
}
});
});