Vishnu
Vishnu

Reputation: 2452

Click to hide any elements

I am just trying to code some simple javascript code to hide any elements in webpage which I click.I am going to use this code as bookmark or in console.

I have written below code so far

var deleteLinks = document.querySelectorAll('.myelement');

Array.from(deleteLinks).forEach(link => {
    link.addEventListener('click', function(event) {
console.log("hi");
             event.preventDefault();
this.remove();

    });
});

What above code does is when I click any element it just hide it.But I need to do following things.

I tried below code , but it gets body class name, How to get the current element classname.

var deleteLinks = document.querySelectorAll('body');

Array.from(deleteLinks).forEach(link => {
    link.addEventListener('click', function(event) {
              event.preventDefault();
console.log(this.className);

    });
});

Upvotes: 0

Views: 68

Answers (1)

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14292

Here is the working sample.

Code Snippet

var deleteLinks = document.querySelectorAll('body *');

Array.from(deleteLinks).forEach(link => {
    link.addEventListener('click', function(event) {
        event.preventDefault();

        if(this.className != '') {
            var combineClassNames = this.className.replace(' ', '.');
            var links = document.querySelectorAll('.' + combineClassNames);

            Array.from(links).forEach(inner => {
                inner.remove();
            });
        }
        else {
            this.remove();
        }
    });
});

Fiddle: https://jsfiddle.net/3fgc5uhv/5/

Upvotes: 1

Related Questions