J Doe Math J Doe Math - 2 years ago 68
Javascript Question

How can I fix my code so that <strike> does not invalidate my Javascript code?

I'm using the following code to create fractions:

<script type='text/javascript'>
$(document).ready(function () {
$('.fraction').each(function(key, value) {
$this = $(this)
var split = $this.html().split("/")
if( split.length == 2 ){
$this.html('<span class="top">'+split[0]+'</span><span class="bottom">'+split[1]+'</span>')

If I have the following code in my body, it successfully formats as a fraction:

<span class="fraction">4/1</span>

If, however, I include a tag, as illustrated below, the function no longer works

<span class="fraction"><strike>4</strike>/1</span>

How can I fix this? Thanks!

Answer Source

Use .text() to strip away the html tags and just get the text.

var split = $this.text().split("/")


If you want to keep the html markup in your result, an easy solution would be to use a different delimiter for your fraction, like a double slash //, a backslash \, or a pipe |. JSFiddle

Using this answer you could also use regex to verify that it only splits if the character isn't found inside <..>. JSFiddle

var split = $this.html().split(/\/(?=[^>]*(?:<|$))/)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download