How do delete elements from page based on cookie value?

I want to create a button on my webpage, which when clicked, sets a cookie with a specified value. The cookie should be valid for the entire domain, all its directories and sub-domains.

The code I’m using now is this:

function setCookie(cname, cvalue, exdays)
        var d = new Date();
        d.setTime(d.getTime() + (365*24*60*60*1000));
        var expires = "expires="+ d.toUTCString();
        document.cookie = cname + "name" + cvalue + "value1" + expires + ";path=/";

Then, once the cookie and its value is set, I want that button to get deleted from the page. Also, next time the page loads, I want to check if the cookie and the value exists and if not, show the button or else, delete the button.

The button in context has an id: delete

I’m using this code to check for cookie and its value:

function getCookie(name)
        var name = privacy + "value1";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');

        for(var i = 0; i <ca.length; i++)
                var c = ca[i];

                while (c.charAt(0) == ' ')
                        c = c.substring(1);

                if (c.indexOf(name) == 0)
                        return c.substring(name.length, c.length);

        return "";

I’ve found these codes from here:

I’m going to use this code to delete the element if the cookie and its value is present:

function removeElement(elementId)
        var element = document.getElementById(delete);

I’ve taken this code from here:

I don’t know how to link those 2 fuctions to carry out the required action.

Hi @hrishi5200, you haven’t copied that code quite correctly; the string "name" should be an equals sign and "value1" a semicolon.

In this code again you forgot the quotes around the element ID, so you’re trying to pass the delete operator which will throw a syntax error (you can see this in the console of your browser dev tools). Together it should go something like

var deleteButton = document.getElementById('delete')

deleteButton.addEventListener('click', function () {
  // Set a cookie for 1 year that the button got clicked 
  setCookie('delete_button_clicked', '1', 365)
  // Remove the button

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.