Как проверить есть ли элемент на странице JS?

Перехожу плавно с jquery на vanilla js. Столкнулся с такой проблемой, когда нету элемента на странице показывает ошибку: Root element must be a existing Html node ну или та которая у других плагинов..

Как проверить есть ли элемент на странице?

ps в jquery юзал это:
$.fn.exists = function(){ return this.length > 0; }

// example
if( $(".price").exists() ) {
       ....
}


вот мой исходник, правильно я вообще начал собирать его?

import Glide from '@glidejs/glide';
import Isotope from 'isotope-layout';
import * as basicScroll from 'basicscroll';
import Masonry from 'masonry-layout';
import imagesLoaded from 'imagesloaded';
import GLightbox from 'glightbox';

const glide_settings = {
	/**
	 * Glide all settings
	 */
	
	init() {
		// Component lenght
		const CustomLength = function (Glide, Components, Events) {
			return {
				mount() {
					Events.emit('slider.length', Components.Sizes.length);
				},
			};
		};

		// Glide settings
		const glide = new Glide('.glide', {
			type: 'carousel',
			gap: '0',
		});

		// Current slide
		const glide_curent = document.querySelector('#glide-current');
		glide.on(['build.after', 'run'], function () {
			glide_curent.innerHTML = glide.index + 1;
		});

		// Total slides
		const glide_total = document.querySelector('#glide-total');
		glide.on('slider.length', (length) => {
			glide_total.innerHTML = length;
		});

		// Glide mount
		glide.mount({
			CustomLength,
		});
	},
};

const back_text = {
	/**
	 * Background text duplicate
	 */
	init() {
		// var back_text = document.querySelectorAll('.back-text');
		// Array.prototype.forEach.call(back_text, function (e) {
		// 	const text_in = e.innerText;
		// 	e.appendChild(document.createElement('span')).textContent = text_in;
		// });

		// const createImg = (el, i) => {
		// 	const img = document.createElement('img');
		// 	img.src = images[~~(Math.random() * images.length)];
		// 	el.appendChild(img);
		// 	setTimeout(() => img.classList.add('animate'), i * 500);
		// };

		// document.querySelectorAll('.result').forEach(createImg);

		// create and duplicate text
		document.querySelectorAll('.back-text').forEach((elem, i) => {
			const text_in = elem.innerText;
			const text_span_create = document.createElement('span');
			const text_span = elem.appendChild(text_span_create);
			text_span.textContent = text_in;
			setTimeout(() => text_span_create.classList.add('animate'), i * 500);
		});
	},
};

const animation = {
	/**
	 * Animation for texts
	 */
	init() {
		var basicScroll = require('basicscroll');
		let parallax_sections = document.querySelectorAll(
			'.back-text span, .history__portfolio-box'
		);
		for (let parallax_section of parallax_sections) {
			let _from = parallax_section.getAttribute('data-from') || '0%';
			let _to = parallax_section.getAttribute('data-to') || '-30%';
			let instance = basicScroll.create({
				elem: parallax_section,
				from: 'top-top',
				to: 'bottom-bottom',
				direct: true,
				props: {
					'--ty': {
						from: _from,
						to: _to,
					},
				},
			});
			instance.start();
		}
	},
};

const smooth_scroll = {
	/**
	 * Smooth scroll to anchor & header fix
	 */
	init() {
		// for header
		const el = document.querySelector('.site__header');
		const observer = new IntersectionObserver(
			([e]) => e.target.classList.toggle('active', e.intersectionRatio < 1),
			{ threshold: [1] }
		);

		observer.observe(el);

		// add anchors
		document.querySelectorAll('a[href^="#"]').forEach((trigger) => {
			trigger.onclick = function (e) {
				e.preventDefault();
				let hash = this.getAttribute('href');
				let target = document.querySelector(hash);
				let headerOffset = 0;
				let elementPosition = target.offsetTop;
				let offsetPosition = elementPosition + headerOffset;

				window.scrollTo({
					top: offsetPosition,
					behavior: 'smooth',
				});
			};
		});
	},
};

const isotope = {
	/**
	 * Smooth scroll to anchor & header fix
	 */
	init() {
		var grid = document.querySelector('.home-portfolio__list');
		var iso;

		imagesLoaded(grid, function () {
			iso = new Isotope(grid, {
				itemSelector: '.portfolio__item',
				percentPosition: true,
				masonry: {
					columnWidth: '.grid-sizer',
				},
			});
		});

		// bind filter button click
		var filtersElem = document.querySelector('.home-portfolio__tags');
		filtersElem.addEventListener('click', function (event) {
			var filterValue = event.target.getAttribute('data-filter');
			iso.arrange({ filter: filterValue });
		});

		// change is-checked class on buttons
		var buttonGroups = document.querySelectorAll('.home-portfolio__tags');
		for (var i = 0, len = buttonGroups.length; i < len; i++) {
			var buttonGroup = buttonGroups[i];
			radioButtonGroup(buttonGroup);
		}

		function radioButtonGroup(buttonGroup) {
			buttonGroup.addEventListener('click', function (event) {
				buttonGroup.querySelector('.active').classList.remove('active');
				event.target.classList.add('active');
			});
		}
	},
};

const glight = {
	/**
	 * Smooth scroll to anchor & header fix
	 */
	init() {
		const lightbox = GLightbox({
			touchNavigation: true,
			loop: false,
			autoplayVideos: true
		});
	},
};

document.addEventListener('DOMContentLoaded', () => {
	glide_settings.init();
	back_text.init();
	animation.init();
	smooth_scroll.init();
	isotope.init();
	glight.init();
});
  • Вопрос задан
  • 567 просмотров
Решения вопроса 1
Stalker_RED
@Stalker_RED
const elem = document.querySelector('#hello .someSelector div');
if (elem) {
  // найден
} else {
  // не найден, elem = null
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@GutsWarhammer
Проще и короче так.
const reviewsSliderTrue = document.querySelector('.js-reviews-slider-init');
reviewsSliderTrue ? reviewsSlider() : false;
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы