Reputation:
I'm trying to remove an em dash from a pre made piece of code. However, it is imbedded in the tree and I cannot seem to access it:
HTML:
<span class="price">
<span class="price">
<span class="amount">£8.75</span>
– // I need this!
<span class="amount">£19.20</span>
</span>
</span>
JS:
$('span.price').each(function(){
$(this)
.find('.amount')
.next()
.remove()
var c = $(this);
var t = c.text();
var b = t.replace('—', '@'); // but if i use ('£', '@') it replaces the pound sign
c.text(b);
});
Would anyone know why the above does not find and replace the '—' dash?
Upvotes: 2
Views: 106
Reputation: 253318
You could use the following:
$('span.price span.amount').each(function(){
if (this.nextSibling) {
this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace(/—/g,'');
}
})
Upvotes: 1
Reputation: 1836
Funny thing :) I copied "-" from html part of jsfiddle into your code
var b = t.replace("–", '@');
and now replace does work. :)
Upvotes: 2
Reputation: 30993
You can get the element content filter only the textnodes and remove them.
Code:
$('span.price').each(function () {
$(this)
.contents()
.filter(function () {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
});
Demo: http://jsfiddle.net/IrvinDominin/fSMKL/
Upvotes: 1
Reputation: 26143
This is simplistic and is for your specific purpose, but does the trick...
$('span.price > span.price').each(function(){
var $this = $(this);
$this.html($this.html().replace("–", ""));
});
Upvotes: 1
Reputation: 78535
You can use a combination of .contents() and .filter to find all text nodes whose content is -
and remove it:
$(".price").contents().filter(function() {
return this.nodeType == 3 && $.trim(this.textContent) === "–";
}).remove();
edit: Changed to use jQuery's trim rather than ES5 as this will work on < IE9
Upvotes: 4
Reputation: 4519
Try below code, it will work
$('span.price').each(function(){
$(this)
.find('.amount')
.next()
.remove()
.end();
var c = $(this);
var t = c.text();
var b = t.replace(/–/g, ' ');
c.text(b);
});
Upvotes: 1