Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(util): use getElementById when it's possible #27031

Merged
merged 1 commit into from
Aug 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions js/src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,20 @@ const Util = (($) => {

getSelectorFromElement(element) {
let selector = element.getAttribute('data-target')
let method = 'querySelector'

if (!selector || selector === '#') {
selector = element.getAttribute('href') || ''
selector = (element.getAttribute('href') || '').trim()
}

const validSelector = selector
if (selector.charAt(0) === '#') {
selector = selector.substr(1)
method = 'getElementById'
}

try {
return document.querySelector(selector) ? selector : null
return document[method](selector) ? validSelector : null
} catch (err) {
return null
}
Expand Down
12 changes: 12 additions & 0 deletions js/tests/unit/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ $(function () {
assert.strictEqual(Util.getSelectorFromElement($el2[0]), null)
})

QUnit.test('Util.getSelectorFromElement should use getElementById', function (assert) {
assert.expect(2)

var spy = sinon.spy(document, 'getElementById')

var $el = $('<div data-target="#7"></div>').appendTo($('#qunit-fixture'))
$('<div id="7" />').appendTo($('#qunit-fixture'))

assert.strictEqual(Util.getSelectorFromElement($el[0]), '#7')
assert.ok(spy.called)
})

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