jQuery 1.4.2, get text and replace first character

I have the following HTML:

<span class="drop_cap">3 <span>Dinners</span></span>

I want to replace that first character. The number will change depending on user interaction, so I can't just grab "3"

I've tried:

$("drop_cap").text().substr(0,1).replace(var);

and

$("drop_cap").html().substr(0,1).replace(var);

and similar things.

TIA

Upvotes: 1

Views: 2402

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92274

jQuery is not very good at dealing with text nodes. Since you know you want to edit the first node (text node) inside the span, you can do the following.

// This inserts 100 in front of that text node inside drop_cap
$("span.drop_cap").each(function(){
    this.firstChild.nodeValue = "100" + this.firstChild.nodeValue;
});

Here's an example that uses String.replace

$("span.drop_cap").each(function(i){
    this.firstChild.nodeValue = this.firstChild.nodeValue.replace(/\d/, i);
});

Example: http://jsfiddle.net/rLGPW/2/, http://jsfiddle.net/rLGPW/3/

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

If you know there's always a number and then some text only, I guess you could use a simple regex to extract the number:

var num = $('span.drop_cap').text().match(/\d+/)[0]

Upvotes: 0

Dnaso
Dnaso

Reputation: 1365

work around, and this is easier especially if you are just using numbers:

<input id='number' type='text' readonly='readonly' value='3'>

NOW YOU CAN USE J-QUERY TO CHANGE THE VALUE OF THE INPUT, which is a ton less buggy than trying to change html.

$("#number").val(var);

and make sure you css the input box because by default it has funky input box style

Upvotes: 0

Related Questions