Rolf B: Dursuchbares Archiv mit <details>

Beitrag lesen

Hallo Gunnar,

ich hab gebastelt und bin damit rausgekommen:

const detailsElements = document.querySelectorAll('details');

document.forms['search-form']?.addEventListener('submit', (event) => {
	event.preventDefault();
	const term = document.forms['search-form'].elements.search.value;
	if (!term) {
		for (let detailsElement of detailsElements) {
			detailsElement.open = false;
		}	
	}	
	else {
		const matcher = new RegExp(`(${term})`, 'gi');
		for (let detailsElement of detailsElements) {
			let html = detailsElement.innerHTML.replace(/<\/?mark>/g, '');
			if (matcher.test(detailsElement.textContent)) {
				html = html.replace(matcher, '<mark>$1</mark>');
				detailsElement.open = true;
			}
			else {
				detailsElement.open = false;
			}
			detailsElement.innerHTML = html;
		}		
	}
});

Die Version, die mir wegen der Polymorphie noch besser gefällt, aber schon unter "write-only" laufen müsste, ist:

const detailsElements = document.querySelectorAll('details');

document.forms['search-form']?.addEventListener('submit', (event) => {
	event.preventDefault();
	const term = document.forms['search-form'].elements.search.value;
	const matcher = term ?
				new RegExp(`(${term})`, 'gi') :
				{ test: () => false };

	for (let detailsElement of detailsElements) {
		let html = detailsElement.innerHTML.replace(/<\/?mark>/g, '');
		detailsElement.open = matcher.test(detailsElement.textContent);
		if (detailsElement.open) {
			html = html.replace(matcher, '<mark>$1</mark>');
		}
		detailsElement.innerHTML = html;
	}
});

Rolf

--
sumpsi - posui - obstruxi