1

If I have the following markup, how can I change just the text within the parent span - with either javascript or jQuery?

<td class="cartItemTotal">
    <span>
        <span class="currency_sign">£</span>
        25.00
    </span>
</td>

I tried the following two (based on two different SO questions), but nothing happens with either.

(1)

$this.find('.cartItemTotal > span').contents().filter(function(){
    return this.nodeType == 3;
}).filter(':first').replaceWith( itemTotal.toFixed(2) );

(2)

$this.find('.cartItemTotal > span')[0].firstChild.data = itemTotal.toFixed(2);

NB: "$this" refers to the current <tr> the table data element resides in.

Community
  • 1
  • 1
verism
  • 1,106
  • 1
  • 12
  • 35

3 Answers3

3

jQuery does'nt really do well with textNodes, but using the native nextSibling you can get the textNode following the .currency_sign element :

$('.currency_sign').get(0).nextSibling.nodeValue = 'new value';

FIDDLE

I'm using get(0) to get the first native DOM element in the collection.

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

Your selectors don't make sense compared to your markup, but if you can get to the .total > span, you can get the DOM element [0], and use .lastChild.

$(".total > span").each(function(i, el) {
    console.log(el.lastChild.data);
});

DEMO: http://jsfiddle.net/Y3m4b/


So your last code example was almost there. Just needed to use .lastChild instead of .firstChild.

$this.find('.cartItemTotal > span')[0].lastChild.data = itemTotal.toFixed(2);
  • @DavidStarkey: Because it's the last child of the `.total > span` element. –  May 16 '13 at 15:30
  • Although the others clearly work in their respective fiddles, this is the only answer that would actually work in my page. Strange, but true. – verism May 16 '13 at 15:44
1

You can play with contents() and filter() to get the textNodes.

var node = $(".cartItemTotal>span").contents().filter(function() {
        return this.nodeType == 3;
    });
node.last().replaceWith( document.createTextNode( "1.99" ));

Running Fiddle: http://jsfiddle.net/eSemE/

epascarello
  • 204,599
  • 20
  • 195
  • 236