Skip to content

Commit

Permalink
Escape ID in Util.getSelectorFromElement
Browse files Browse the repository at this point in the history
  • Loading branch information
Johann-S committed Nov 7, 2017
1 parent 26dc17b commit 5268aa0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
9 changes: 9 additions & 0 deletions js/src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ const Util = (($) => {
}
}

// Thanks to learn.jquery.com see : http://bit.ly/1Tyr4SZ
function escapeId(selector) {
return selector.replace(/(:|\.|\[|\]|,|=|@)/g, '\\$1')
}

/**
* --------------------------------------------------------------------------
Expand All @@ -112,6 +116,11 @@ const Util = (($) => {
selector = element.getAttribute('href') || ''
}

// if it's an ID
if (selector.charAt(0) === '#') {
selector = escapeId(selector)
}

try {
const $selector = $(document).find(selector)
return $selector.length > 0 ? selector : null
Expand Down
8 changes: 7 additions & 1 deletion js/tests/unit/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@ $(function () {
QUnit.module('util')

QUnit.test('Util.getSelectorFromElement should return the correct element', function (assert) {
assert.expect(2)
assert.expect(3)

var $el = $('<div data-target="body"></div>').appendTo($('#qunit-fixture'))
assert.strictEqual(Util.getSelectorFromElement($el[0]), 'body')

// not found element
var $el2 = $('<div data-target="#fakeDiv"></div>').appendTo($('#qunit-fixture'))
assert.strictEqual(Util.getSelectorFromElement($el2[0]), null)

// should escape ID and found the correct element
var $el3 = $('<div data-target="#collapse:Example"></div>').appendTo($('#qunit-fixture'))
$('<div id="collapse:Example"></div>').appendTo($('#qunit-fixture'))
assert.strictEqual(Util.getSelectorFromElement($el3[0]), '#collapse\\:Example')
})

QUnit.test('Util.typeCheckConfig should thrown an error when a bad config is passed', function (assert) {
Expand Down

0 comments on commit 5268aa0

Please sign in to comment.