souporserious
souporserious

Reputation: 2157

Adding span to numbers using Jquery

So I have been dabbling around in jQuery a bit this week. Trying to add some cool things to a wordpress theme I am currently working on.

With the help of this wonderful site, I received the following JS to wrap a span around numbers in a certain div. All was well until I started implementing more JS to find out this is actually causing my other JS to break.

//add span to numbers
var elem = document.getElementById('passage');
elem.innerHTML = elem.innerHTML.replace(/\b(\d+)\b/g, '<span>$1</span>');

However, I was informed since I am using jQuery, to take "document.getElementById" out and end up with this:

//add span to numbers
var elem = $( 'passage' );
elem.innerHTML = elem.innerHTML.replace( /\b(\d+)\b/g, '<span>$1</span>' );

I figured this would solve the situation with no luck. Any ideas of why this isn't working? Thanks

My end result is to be able to style numbers like this site does for their Bible verses: http://marshill.com/media/the-seven/lukewarm-in-laodicea-comfort-and-convenience-before-christ#scripture

Upvotes: 3

Views: 789

Answers (2)

David Thomas
David Thomas

Reputation: 253426

If you're selecting by the id you need the CSS-alike id selector:

var elem = $('#passage');,

To select by class:

var elems = $('.className');

Using the $('#passage') selector, you end up with a jQuery object, rather than a DOM-node, so $('#passage').innerHTML (or elem.innerHTML) returns an error: Uncaught TypeError: Cannot call method 'replace' of undefined in Chromium 19.

To work around that, you can 'drop' back to a DOM-node with:

elem.innerHTML = $('#passage')[0].innerHTML.replace(/*...*/);

Or instead use jQuery:

elem.html(function(i,oldHTML){
    return oldHTML.replace( /\b(\d+)\b/g, '<span>$1</span>' );
});​

JS Fiddle demo.

References:

Upvotes: 5

Corey
Corey

Reputation: 123

For the first line, when working with ids, you want to prepend the string with a pound symbol; that is, $('#passage').

For the second line, note that doing $('#passage') returns a jQuery object, so you can't use standard methods on it. You should be using jQuery methods. The equivalent for innerHTML is .html().

So you would want to do the following:

//add span to numbers
var elem = $( '#passage' );
elem.html(elem.html().replace( /\b(\d+)\b/g, '<span>$1</span>' ));

A little ugly, but it gets the job done. David's answer is slightly more eloquent.

Upvotes: 3

Related Questions