J Doe Math J Doe Math - 10 months ago 25
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!


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(/\/(?=[^>]*(?:<|$))/)