Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 784
souporserious Avatar asked Aug 16 '26 09:08

souporserious


2 Answers

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:

  • jQuery selectors.
  • html().
like image 166
David Thomas Avatar answered Aug 18 '26 23:08

David Thomas


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.

like image 32
Corey Avatar answered Aug 18 '26 21:08

Corey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!