Search code examples
javascriptdom

How to appendChild in all the elements in loop having specific Text in javascript?


I am creating a Dynamic Tree of elements by using an Array Values maintaining the level by attribute value of Parent, which match from the element Button Text I later on use as accordion.

here the issue coming is, it does not create element for all the elements having that specific Text

I have even used the For Loop and then try to insert with nextElementSibling as you can see in below function

function appendSymptomToForm(symptom, symptomElements, container) {
    if (symptom.parent === 'none') {
        symptomForm.appendChild(container);
    } else {
        
var aTags = document.getElementsByTagName("button");
var searchText = symptom.parent;
var found;

for (var i = 0; i < aTags.length; i++) {    
  if (aTags[i].textContent == searchText) {  

    found = aTags[i].nextElementSibling;    
            found.insertBefore(container, found.nextElementSibling);
  }
}
    }
    console.log(`Symptom ${symptom.text} appended to the form.`);
}

Below is exactly the Line of Code which append the Child element.

found.insertBefore(container, found.nextElementSibling);

Below I have created the fiddle which give you full understanding, that I have 3 Levels in the array named, window.symptomData. Every element add according to its Parent Attribute

for example note second Level B:

{ depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de ore' }

Here you will see that there are multiple buttons of second Level B but it add Third Level only under the Last Element

Please refer the function appendSymptomToForm in the fiddle, where it does appendChild

Working Fiddle

window.symptomData = [
    { depth: 0, text: 'De aproximativ', parent: 'none', tooltip: 'Perioadă nespecificată de timp, folosită pentru estimări' },
    { depth: 1, text: '1', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
    { depth: 1, text: '2', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
    { depth: 1, text: '3', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
    { depth: 1, text: '4', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
    
    { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în ore' },
    { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în zile' },
    { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată de timp' },    
    { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în luni' },
    { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în ani' },

    { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în ore' },
    { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în zile' },
    { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în săptămâni' },
    { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în luni' },
    { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în ani' },

    { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în ore' },
    { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în zile' },
    { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în săptămâni' },
    { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în luni' },
    { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în ani' },
    
    { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în ore' },
    { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în zile' },
    { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în săptămâni' },
    { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în luni' },
    { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în ani' },
    
    { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de ore' },
    { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de zile' },
    { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de săptămâni' },
    { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de luni' },
    { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de ani' },
    
    { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de ore' },
    { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de zile' },
    { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de săptămâni' },
    { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de luni' },
    { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de ani' },
];

// script.js
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOMContentLoaded event triggered, initializing symptoms setup...');
    const symptomData = window.symptomData; // Now pulling from the global variable set by sd.js

    const symptomForm = document.getElementById('symptomForm');
    if (!symptomForm) {
        console.error('Failed to find symptom form on the page.');
        return;
    }

    let symptomElements = {};
    const tooltipDiv = document.createElement('div');
    setupTooltipDiv(tooltipDiv);
    document.body.appendChild(tooltipDiv);

    symptomData.forEach(symptom => {
        const container = document.createElement('div');
        setupSymptomContainer(symptom, container);

        const button = document.createElement('button');
        setupSymptomButton(symptom, button, container);

        const childrenContainer = document.createElement('div');
        setupChildrenContainer(childrenContainer, container);

        symptomElements[symptom.text] = { button, container, childrenContainer };

        setupButtonEvents(button, childrenContainer);
        appendSymptomToForm(symptom, symptomElements, container);
    });

    setupSendButton();
});

function setupTooltipDiv(tooltipDiv) {
    tooltipDiv.id = 'tooltipDiv';
    tooltipDiv.style = "position: fixed; bottom: 20px; left: 20px; padding: 10px; " +
                       "background-color: rgba(0, 0, 0, 0.75); color: white; border-radius: 5px; display: none;";
    console.log('Tooltip div setup completed.');
}

function setupSymptomContainer(symptom, container) {
    container.className = `symptom-instance depth-${symptom.depth}`;
    console.log(`Setup container for symptom: ${symptom.text}`);
}

function setupSymptomButton(symptom, button, container) {
    button.textContent = symptom.text;
    button.className = 'symptom-button';
    button.title = symptom.tooltip;
    container.appendChild(button);
    console.log(`Button created for symptom: ${symptom.text}`);
}

function setupChildrenContainer(childrenContainer, container) {
    childrenContainer.className = 'sub-symptoms hidden';
    container.appendChild(childrenContainer);
    console.log('Children container setup completed.');
}

function setupButtonEvents(button, childrenContainer) {
    button.onclick = () => {
        childrenContainer.classList.toggle('hidden');
        button.classList.toggle('pressed');
        scrollToButton(button);
        console.log(`Visibility toggled for: ${button.textContent}, New state: ${childrenContainer.className}`);
    };
    button.addEventListener('touchstart', () => showTooltip(button, button.title), { passive: true });
    button.addEventListener('touchend', hideTooltip, { passive: true });
}

function appendSymptomToForm(symptom, symptomElements, container) {
       if (symptom.parent === 'none') {
        symptomForm.appendChild(container);
    } else {
        
var aTags = document.getElementsByTagName("button");
var searchText = symptom.parent;
var found;

for (var i = 0; i < aTags.length; i++) {    
  if (aTags[i].textContent == searchText) {  

    found = aTags[i].nextElementSibling;    
            found.insertBefore(container, found.nextElementSibling);
  }
}
    }
    console.log(`Symptom ${symptom.text} appended to the form.`);
}

function scrollToButton(button) {
    const buttonRect = button.getBoundingClientRect();
    const visibleAreaStart = window.innerHeight / 4;
    const scrollYOffset = buttonRect.top - visibleAreaStart + window.scrollY;
    window.scrollTo({
        top: scrollYOffset,
        behavior: 'smooth'
    });
    console.log(`Scrolled to button: ${button.textContent}`);
}

function setupSendButton() {
    const sendButton = document.createElement('button');
    sendButton.textContent = 'Copiaza Selectate';
    sendButton.addEventListener('click', () => {
        const selectedSymptoms = Array.from(document.querySelectorAll('.symptom-button.pressed'))
            .map(btn => btn.textContent.trim())
            .join(', ');
        navigator.clipboard.writeText(selectedSymptoms)
            .then(() => {
                console.log('Selected symptoms copied to clipboard.');
                alert('Selected symptoms copied to clipboard.');
            })
            .catch(err => {
                console.error('Error copying to clipboard:', err);
                alert('Failed to copy symptoms. See console for errors.');
            });
    });
    document.body.appendChild(sendButton);
    console.log('Send button setup completed.');
}

function showTooltip(button, text) {
    const tooltipDiv = document.getElementById('tooltipDiv');
    tooltipDiv.textContent = text;
    tooltipDiv.style.display = 'block';
    console.log(`Tooltip shown for ${button.textContent}: ${text}`);
}

function hideTooltip() {
    const tooltipDiv = document.getElementById('tooltipDiv');
    tooltipDiv.style.display = 'none';
    console.log('Tooltip hidden.');
}
    <div id="symptomForm">
    </div>


Solution

  • The problem is in the appendSymptomToForm function where the container (child) is being inserted.

    This code is just transferring the container from once place to another (first parent, second, ... fifth). It is one child being moved.

                for (var i = 0; i < aTags.length; i++) {
                    if (aTags[i].textContent == searchText) {
    
                        found = aTags[i].nextElementSibling;
                        found.insertBefore(container, found.nextElementSibling);
                    }
                }
    

    What you need to do is to have a copy/clone of the container (child) before inserting it. Something like:

    var clonedContainer = container.cloneNode(true);
    

    That's the child that has to be inserted:

    found.insertBefore(clonedContainer, found.nextElementSibling);
    

    Your function should be like this:

        function appendSymptomToForm(symptom, symptomElements, container) {
            if (symptom.parent === 'none') {
                symptomForm.appendChild(container);
            } else {
    
                var aTags = document.getElementsByTagName("button");
                var searchText = symptom.parent;
                var found;
    
                for (var i = 0; i < aTags.length; i++) {
                    if (aTags[i].textContent == searchText) {
                        var clonedContainer = container.cloneNode(true);
                        found = aTags[i].nextElementSibling;
                        found.insertBefore(clonedContainer, found.nextElementSibling);
                    }
                }
            }
            console.log(`Symptom ${symptom.text} appended to the form.`);
        }
    

    EDIT: From your updated code, the reason why setupButtonEvents function does not work as expected is that the childrenContainer is no longer connected to the container after clone.

    To resolve it, you need to modify your setupButtonEvents function and transfer below code in a separate function:

    button.onclick = () => {
        childrenContainer.classList.toggle('hidden');
        button.classList.toggle('pressed');
        scrollToButton(button);
        console.log(`Visibility toggled for: ${button.textContent}, New state: ${childrenContainer.className}`);
    };
    

    So your setupButtonEvents function will be:

        function setupButtonEvents(button, childrenContainer) {
            button.addEventListener('touchstart', () => showTooltip(button, button.title), { passive: true });
            button.addEventListener('touchend', hideTooltip, { passive: true });
        }
    

    Then create new function for the button click event:

        function setupButtonClick() {
            document.querySelectorAll('.symptom-button').forEach(function (button) {
                button.onclick = () => {
                    const childrenContainer = button.parentNode.querySelectorAll('.sub-symptoms');
                    childrenContainer[0].classList.toggle('hidden');
                    button.classList.toggle('pressed');
                    scrollToButton(button);
                    console.log(`Visibility toggled for: ${button.textContent}, New state: ${childrenContainer.className}`);
                };
            });
        }
    

    Then call that new function after all buttons has been setup (last line here):

        document.addEventListener('DOMContentLoaded', function () {
            console.log('DOMContentLoaded event triggered, initializing symptoms setup...');
           ...
           setupButtonClick();
        }
    

    Here is the working code:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            .symptom-instance {
                margin-top: 5px;
                padding-left: 20px;
                border-left: 4px solid;
                position: relative;
                min-height: 20px;
                /* asigură că are înălțime minimă */
                min-width: 100px;
                /* asigură că are lățime minimă */
            }
    
            /* Culori și background-uri specificate pentru diferite nivele */
            .symptom-instance.depth-0 {
                border-left-color: #4285F4;
                background-color: rgba(66, 133, 244, 0.1);
            }
    
            .symptom-instance.depth-1 {
                border-left-color: #34A853;
                background-color: rgba(52, 168, 83, 0.1);
            }
    
            .symptom-instance.depth-2 {
                border-left-color: #FBBC05;
                background-color: rgba(251, 188, 5, 0.1);
            }
    
            .symptom-instance.depth-3 {
                border-left-color: #EA4335;
                background-color: rgba(234, 67, 53, 0.1);
            }
    
            .symptom-instance.depth-4 {
                border-left-color: #673AB7;
                background-color: rgba(103, 58, 183, 0.1);
            }
    
            .symptom-instance.depth-5 {
                border-left-color: #FF5722;
                background-color: rgba(255, 87, 34, 0.1);
            }
    
            /* Asigură că butoanele sunt vizibile și accesibile */
            .symptom-button {
                display: block;
                margin: 5px 0;
                color: white;
                background-color: #444;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
                cursor: pointer;
                transition: background-color 0.3s;
            }
    
            .symptom-button:hover,
            .symptom-button.pressed {
                background-color: #4CAF50;
                /* Verde la hover */
            }
    
            .hidden {
                display: none !important;
                visibility: hidden !important;
                /* Asigură că elementul este complet ascuns */
                opacity: 0;
                /* Oprește interacțiunea cu elementul chiar dacă ar fi vizibil accidental */
            }
    
            .visible {
                display: block !important;
                visibility: visible !important;
                /* Asigură vizibilitatea completă */
                opacity: 1;
                /* Reset la opacitate normală */
                width: auto;
                /* Elimină restricțiile de lățime */
                height: auto;
                /* Elimină restricțiile de înălțime */
                min-width: 1px;
                /* Previne colapsul elementului la lățimi 0 */
                min-height: 1px;
                /* Previne colapsul elementului la înălțimi 0 */
            }
    
    
            /* Tooltip pentru imagini */
            .tooltip-image {
                position: absolute;
                width: 200px;
                height: auto;
                display: none;
                z-index: 1000;
                border: 1px solid #ccc;
                box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
            }
    
            .symptom-button:hover+.tooltip-image {
                display: block;
            }
    
            /* Media queries pentru ajustarea elementelor la diferite dimensiuni ale ecranului */
            @media (max-width: 768px) {
                body {
                    padding: 5px;
                }
    
                .container {
                    padding: 5vw;
                }
    
                button,
                textarea {
                    padding: 12px;
                }
            }
    
            @media (min-width: 768px) {
    
                button,
                textarea {
                    padding: 15px;
                }
            }
        </style>
    </head>
    
    <body>
        <div id="symptomForm">
        </div>
        <script>
            window.symptomData = [
                { depth: 0, text: 'De aproximativ', parent: 'none', tooltip: 'Perioadă nespecificată de timp, folosită pentru estimări' },
                { depth: 1, text: '1', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
                { depth: 1, text: '2', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
                { depth: 1, text: '3', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
                { depth: 1, text: '4', parent: 'De aproximativ', tooltip: 'Al doilea nivel de timp estimat, similar cu primul' },
    
                { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în ore' },
                { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în zile' },
                { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată de timp' },
                { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în luni' },
                { depth: 2, text: 'second level A', parent: '1', tooltip: 'Durată exprimată în ani' },
    
                { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în ore' },
                { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în zile' },
                { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în săptămâni' },
                { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în luni' },
                { depth: 2, text: 'second level B', parent: '2', tooltip: 'Durată exprimată în ani' },
    
                { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în ore' },
                { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în zile' },
                { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în săptămâni' },
                { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în luni' },
                { depth: 2, text: 'second level B', parent: '3', tooltip: 'Durată exprimată în ani' },
    
                { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în ore' },
                { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în zile' },
                { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în săptămâni' },
                { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în luni' },
                { depth: 2, text: 'second level B', parent: '4', tooltip: 'Durată exprimată în ani' },
    
                { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de ore' },
                { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de zile' },
                { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de săptămâni' },
                { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de luni' },
                { depth: 3, text: 'Third level A', parent: 'second level A', tooltip: 'Descrie simptomele după o perioadă de ani' },
    
                { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de ore' },
                { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de zile' },
                { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de săptămâni' },
                { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de luni' },
                { depth: 3, text: 'Third level B', parent: 'second level B', tooltip: 'Descrie simptomele după o perioadă de ani' },
            ];
    
            //doc.js
    
            console.log("Checking if elements exist:");
            console.log("Sub-symptoms elements count:", document.querySelectorAll('.sub-symptoms').length);
    
    
    
    
            function toggleVisibility(selector) {
                const elements = document.querySelectorAll(selector);
                if (elements.length === 0) {
                    console.log(`No elements found for selector ${selector}`);
                    return; // Exit the function early if no elements are found
                }
    
                console.log(`Toggling visibility for elements with selector: ${selector}`);
                elements.forEach(element => {
                    if (element.classList.contains('hidden')) {
                        element.classList.remove('hidden');
                        element.classList.add('visible');
                        console.log('Element is now visible.');
                    } else {
                        element.classList.remove('visible');
                        element.classList.add('hidden');
                        console.log('Element is now hidden.');
                    }
                });
            }
    
    
    
            // Logging function to inspect children and their visibility
            function inspectChildren(parentSelector) {
                const parent = document.querySelector(parentSelector);
                if (!parent) {
                    console.error('Inspect children failed: No parent found for selector', parentSelector);
                    return;
                }
    
                const children = parent.querySelectorAll(':scope > .sub-symptoms');
                console.log(`Inspecting children of parent with selector "${parentSelector}"`, 'Total children:', children.length);
    
                children.forEach((child, index) => {
                    console.log(`Child ${index + 1}: Visibility -`, child.classList.contains('hidden') ? 'Hidden' : 'Visible');
                });
            }
    
            // Setup for the send button with logging
            function setupSendButton() {
                const sendButton = document.createElement('button');
                sendButton.textContent = 'Copy Selected';
                sendButton.addEventListener('click', () => {
                    const selectedSymptoms = Array.from(document.querySelectorAll('.symptom-button.pressed'))
                        .map(btn => btn.textContent.trim())
                        .join(', ');
                    console.log('Attempting to copy to clipboard:', selectedSymptoms);
    
                    navigator.clipboard.writeText(selectedSymptoms).then(() => {
                        console.log('Clipboard operation successful.');
                        alert('Selected symptoms copied to clipboard.');
                    }).catch(err => {
                        console.error('Clipboard operation failed:', err);
                        alert('Failed to copy symptoms. See console for errors.');
                    });
                });
                document.body.appendChild(sendButton);
                console.log('Send button setup completed.');
            }
    
            // Initialization with detailed logging
            document.addEventListener('DOMContentLoaded', () => {
                console.log('Document fully loaded and DOM fully initialized.');
                setupSendButton();
                toggleVisibility('.sub-symptoms'); // Example use case, adjust as needed for your HTML structure
    
                // Inspecting children elements on document ready or after a specific interaction
                //inspectChildren('#someParentElement'); // Replace '#someParentElement' with your actual parent element selector
            });
    
    
            // script.js
            document.addEventListener('DOMContentLoaded', function () {
                console.log('DOMContentLoaded event triggered, initializing symptoms setup...');
                const symptomData = window.symptomData; // Now pulling from the global variable set by sd.js
    
                const symptomForm = document.getElementById('symptomForm');
                if (!symptomForm) {
                    console.error('Failed to find symptom form on the page.');
                    return;
                }
    
                let symptomElements = {};
                const tooltipDiv = document.createElement('div');
                setupTooltipDiv(tooltipDiv);
                document.body.appendChild(tooltipDiv);
    
                symptomData.forEach(symptom => {
                    const container = document.createElement('div');
                    setupSymptomContainer(symptom, container);
    
                    const button = document.createElement('button');
                    setupSymptomButton(symptom, button, container);
    
                    const childrenContainer = document.createElement('div');
                    setupChildrenContainer(childrenContainer, container);
    
                    symptomElements[symptom.text] = { button, container, childrenContainer };
    
                    setupButtonEvents(button, childrenContainer);
                    appendSymptomToForm(symptom, symptomElements, container);
                });
    
                setupSendButton();
                setupButtonClick()
    
            });
    
            function setupTooltipDiv(tooltipDiv) {
                tooltipDiv.id = 'tooltipDiv';
                tooltipDiv.style = "position: fixed; bottom: 20px; left: 20px; padding: 10px; " +
                    "background-color: rgba(0, 0, 0, 0.75); color: white; border-radius: 5px; display: none;";
                console.log('Tooltip div setup completed.');
            }
    
            function setupSymptomContainer(symptom, container) {
                container.className = `symptom-instance depth-${symptom.depth}`;
                console.log(`Setup container for symptom: ${symptom.text}`);
            }
    
            function setupSymptomButton(symptom, button, container) {
                button.textContent = symptom.text;
                button.className = 'symptom-button';
                button.title = symptom.tooltip;
                container.appendChild(button);
                console.log(`Button created for symptom: ${symptom.text}`);
            }
    
            function setupChildrenContainer(childrenContainer, container) {
                childrenContainer.className = 'sub-symptoms hidden';
                container.appendChild(childrenContainer);
                console.log('Children container setup completed.');
            }
    
            function setupButtonEvents(button, childrenContainer) {
                button.addEventListener('touchstart', () => showTooltip(button, button.title), { passive: true });
                button.addEventListener('touchend', hideTooltip, { passive: true });
            }
    
            function setupButtonClick() {
                document.querySelectorAll('.symptom-button').forEach(function (button) {
                    button.onclick = () => {
                        const childrenContainer = button.parentNode.querySelectorAll('.sub-symptoms');
                        childrenContainer[0].classList.toggle('hidden');
                        button.classList.toggle('pressed');
                        scrollToButton(button);
                        console.log(`Visibility toggled for: ${button.textContent}, New state: ${childrenContainer.className}`);
                    };
                });
            }
    
            function appendSymptomToForm(symptom, symptomElements, container) {
                if (symptom.parent === 'none') {
                    symptomForm.appendChild(container);
                } else {
    
                    var aTags = document.getElementsByTagName("button");
                    var searchText = symptom.parent;
                    var found;
    
                    for (var i = 0; i < aTags.length; i++) {
                        if (aTags[i].textContent == searchText) {
                            var clonedContainer = container.cloneNode(true);
                            found = aTags[i].nextElementSibling;
                            found.insertBefore(clonedContainer, found.nextElementSibling);
                        }
                    }
                }
                console.log(`Symptom ${symptom.text} appended to the form.`);
            }
    
            function scrollToButton(button) {
                const buttonRect = button.getBoundingClientRect();
                const visibleAreaStart = window.innerHeight / 4;
                const scrollYOffset = buttonRect.top - visibleAreaStart + window.scrollY;
                window.scrollTo({
                    top: scrollYOffset,
                    behavior: 'smooth'
                });
                console.log(`Scrolled to button: ${button.textContent}`);
            }
    
            function setupSendButton() {
                const sendButton = document.createElement('button');
                sendButton.textContent = 'Copiaza Selectate';
                sendButton.addEventListener('click', () => {
                    const selectedSymptoms = Array.from(document.querySelectorAll('.symptom-button.pressed'))
                        .map(btn => btn.textContent.trim())
                        .join(', ');
                    navigator.clipboard.writeText(selectedSymptoms)
                        .then(() => {
                            console.log('Selected symptoms copied to clipboard.');
                            alert('Selected symptoms copied to clipboard.');
                        })
                        .catch(err => {
                            console.error('Error copying to clipboard:', err);
                            alert('Failed to copy symptoms. See console for errors.');
                        });
                });
                document.body.appendChild(sendButton);
                console.log('Send button setup completed.');
            }
    
            function showTooltip(button, text) {
                const tooltipDiv = document.getElementById('tooltipDiv');
                tooltipDiv.textContent = text;
                tooltipDiv.style.display = 'block';
                console.log(`Tooltip shown for ${button.textContent}: ${text}`);
            }
    
            function hideTooltip() {
                const tooltipDiv = document.getElementById('tooltipDiv');
                tooltipDiv.style.display = 'none';
                console.log('Tooltip hidden.');
            }
        </script>
    </body>
    
    </html>