user1469270
user1469270

Reputation:

Remove character from code with jQuery

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:

jsFiddle

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

Answers (6)

David Thomas
David Thomas

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

Mr.TK
Mr.TK

Reputation: 1836

Funny thing :) I copied "-" from html part of jsfiddle into your code

var b = t.replace("–", '@');

and now replace does work. :)

http://jsfiddle.net/bhAtn/7/

Upvotes: 2

Irvin Dominin
Irvin Dominin

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

Reinstate Monica Cellio
Reinstate Monica Cellio

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("–", ""));
});

jsfiddle example

Upvotes: 1

CodingIntrigue
CodingIntrigue

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();

jsFiddle

edit: Changed to use jQuery's trim rather than ES5 as this will work on < IE9

Upvotes: 4

Dimag Kharab
Dimag Kharab

Reputation: 4519

DEMO

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

Related Questions