rainshark
rainshark

Reputation: 45

How to remove a div in a site using a Chrome extension?

There's this div in a site:

<div class="section1">
....
</div>

I want to remove it using a Chrome extension... Can someone give only the javascript code alone? Thanks.

Upvotes: 1

Views: 3736

Answers (3)

Martijn
Martijn

Reputation: 13632

function removeElementsByClassName(names) {
    var els = document.getElementsByClassName(names),
        i, element;
    for (i = els.count - 1; i > 0; i -= 1) {
        element = els[i];
        element.parentElement.removeChild(element);
    }
}

removeElementsByClassName('section1');

Upvotes: 3

serg
serg

Reputation: 111365

If by removing you simply mean hiding then you can run this from a content script:

document.querySelector('div.section1').style.display = 'none';

(this assumes there is only 1 section1 element on the page, otherwise you would need to use document.querySelectorAll and filter the results based on some criteria)

Upvotes: 1

James T
James T

Reputation: 3320

function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert("Child div has already been removed or does not exist.");
          return false;
     }
}

removeElement('parent','child');

Upvotes: 2

Related Questions