Commit 6ab12777 authored by winh's avatar winh

Introduce addClassIfElementExists utility

parent a61eda78
......@@ -2,6 +2,7 @@
import AjaxFilter from '~/droplab/plugins/ajax_filter';
import './filtered_search_dropdown';
import { addClassIfElementExists } from '../lib/utils/dom_utils';
class DropdownUser extends gl.FilteredSearchDropdown {
constructor(droplab, dropdown, input, tokenKeys, filter) {
......@@ -32,11 +33,7 @@ class DropdownUser extends gl.FilteredSearchDropdown {
}
hideCurrentUser() {
const currentUserItem = this.dropdown.querySelector('.js-current-user');
if (currentUserItem) {
currentUserItem.classList.add('hidden');
}
addClassIfElementExists(this.dropdown.querySelector('.js-current-user'), 'hidden');
}
itemClicked(e) {
......
......@@ -3,6 +3,7 @@ import RecentSearchesRoot from './recent_searches_root';
import RecentSearchesStore from './stores/recent_searches_store';
import RecentSearchesService from './services/recent_searches_service';
import eventHub from './event_hub';
import { addClassIfElementExists } from '../lib/utils/dom_utils';
class FilteredSearchManager {
constructor(page) {
......@@ -227,11 +228,7 @@ class FilteredSearchManager {
}
addInputContainerFocus() {
const inputContainer = this.filteredSearchInput.closest('.filtered-search-box');
if (inputContainer) {
inputContainer.classList.add('focus');
}
addClassIfElementExists(this.filteredSearchInput.closest('.filtered-search-box'), 'focus');
}
removeInputContainerFocus(e) {
......
/* eslint-disable import/prefer-default-export */
export const addClassIfElementExists = (element, className) => {
if (element) {
element.classList.add(className);
}
};
import { addClassIfElementExists } from '~/lib/utils/dom_utils';
describe('DOM Utils', () => {
describe('addClassIfElementExists', () => {
const className = 'biology';
const fixture = `
<div class="parent">
<div class="child"></div>
</div>
`;
let parentElement;
beforeEach(() => {
setFixtures(fixture);
parentElement = document.querySelector('.parent');
});
it('adds class if element exists', () => {
const childElement = parentElement.querySelector('.child');
expect(childElement).not.toBe(null);
addClassIfElementExists(childElement, className);
expect(childElement.classList).toContain(className);
});
it('does not throw if element does not exist', () => {
const childElement = parentElement.querySelector('.other-child');
expect(childElement).toBe(null);
addClassIfElementExists(childElement, className);
});
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment