icicleking
icicleking

Reputation: 1077

Remove a character from the middle of a string: without removing inner element

This one has me stumped. I want to remove the "+" from a label element. Here's the HTML:

 <label class="option" for="edit-attributes-21-33">
 <input type="radio" id="edit-attributes-21-33" name="attributes[21]" 
 value="33" checked="checked" class="form-radio"> 4 oz, +$15.00</label>

I started with this

$(".option").each(function(index, value) {

$(this).text( $(this).text().replace("+", ""));

})

This removes the "+" but also strips out the input element. So then I tried:

$(".option").each(function(index, value) {

var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).text(newString);

})

This makes a string of the correct html mark-up, but it's a string and is passed back to the DOM that way. I've seen another post with the same problem, but no solution.

Upvotes: 9

Views: 3001

Answers (3)

Martijn
Martijn

Reputation: 16123

What you're looking for is called a textNode. I gave your label an ID to make it easier, but the priciple remains the same for other selectors:

var node = document.getElementById("example").childNodes[2];
node.nodeValue = node.nodeValue.replace("+", "");

With a simple demo.
You should try to use plain JS as much as you can in favour in jQuery. Plain JS is often a lot faster than jQuery is.

After the comment, if you don't know the exact position of the textnode, check this.

Upvotes: 4

emerson.marini
emerson.marini

Reputation: 9348

Late answer, just for the sake of showing a different approach using jQuery.

Here you would keep the input state, and wouldn't have the risk of replacing chars that you don't want to. Let's say you used + somewhere else, not just on the label text.

$(function () {
    $('label.option').each(function () {
        var label = $(this);
        var input = $('input.form-radio', this);
        var text = label.text();

        // Clean up the label contents.
        label.empty();        

        // Replace the char occurrences.
        text = text.replace(/\+/g, "");

        // Append both the input and the modified text.
        label.append(input).append(text);        
    });
});

Demo

Upvotes: 0

Darkseal
Darkseal

Reputation: 9564

You can achieve what you want using your code by using .html() instead of .text():

$(".option").each(function(index, value) {
    var oldString = $(this).html();
    var newString = oldString.replace("+", "");
    console.log(oldString, newString);
    $(this).html(newString);
});

Here's the JQuery .html() method ref: https://api.jquery.com/html/

Here's the Fiddle: https://jsfiddle.net/Darkseal/1c572Luw/

I also slightly modified your <input> end tag to make it XHTML compliant.

Upvotes: 6

Related Questions