Jquery select only part of a div
Sorry if it is a basic question but I am stuck. I am trying to change the price in the following code:
<body>
<div id="price">
<span class="title"> price</span>
开发者_运维技巧 $30
</div>
</body>
I tried that:
<script type="text/javascript">
$('#price').text('$31');
</script>
but of course it remove the span. I tried a few combinations with .not but nothing seems to work. Unfortunately, I cannot add a class to the price, which would make my life easier. Anybody knows how to do that ?
contents()
returns all children including text nodes. Then you just get only the text nodes with a filter()
, and voila.
$('#price').contents().filter(function (index) {
return this.nodeType == 3 && index == 2; // both conditions to make sure it's the correct node
}).replaceWith(' $31');
How about using a RegExp replace like:
var $price = $('#price'),
priceHTML = $price.html(),
newPrice = '$31';
$price.html(priceHTML.replace(/\$\d+/, newPrice));
See example →
Add a label or span around the $30 and then change that.
Try formatting your HTML like so:
<div id="priceContainer">
<span class="title">price</span>
<span id="price">$30</span>
</div>
And the jQuery just as it is, really:
<script type="text/javascript">
$("#price").text("$31");
</script>
精彩评论