Use a MutationObserver to watch the DOM for a SweetAlert2 popup (.swal2-popup). When it appears, replace the title, description, and button text, and optionally keep any existing list (<ul>) inside the description.
JavaScript
// Start observing the DOM for the SweetAlert2 popup
const observer = new MutationObserver(() => {
const popup = document.querySelector('.swal2-popup');
if (!popup) return;
// Prevent multiple modifications of the same popup
if (popup.getAttribute('data-modified') === 'true') return;
const title = popup.querySelector('.swal2-title');
const description = popup.querySelector('.swal2-html-container');
const button = popup.querySelector('.swal2-confirm');
// If the description already contains a <ul>, we'll re-append it after changing text
const descriptionElements = description ? description.querySelector('ul') : null;
if (title) {
title.textContent = 'Example title';
}
if (description) {
// Replace description text
description.textContent = 'Example description';
// If a list existed, keep it and add a helper class for layout tweaks
if (descriptionElements) {
description.classList.add('custom');
description.appendChild(descriptionElements);
}
}
if (button) {
button.textContent = 'Example button';
}
// Mark as modified to avoid repeated updates
popup.setAttribute('data-modified', 'true');
});
// Begin observing the whole document for added nodes
observer.observe(document.body, { childList: true, subtree: true });
// (Optional) If you want to stop observing after the first modification, you can disconnect:
// observer.disconnect();
CSS
.swal2-html-container.custom {
display: flex !important;
flex-direction: column;
gap: 5px;
align-items: center;
}
Notes
- This snippet targets SweetAlert2 default classes:
.swal2-popup,.swal2-title,.swal2-html-container, and.swal2-confirm. - The
data-modified="true"flag prevents re-running the updates for the same popup. - If your popup content is dynamic or re-rendered often, keep the observer active; otherwise, disconnect it after the first change.
Comments
0 comments
Please sign in to leave a comment.