2

I try to add a class to an element on Facebook page with a chrome extension. Unfortunately my script does not work... My goal is to select the posts containing an ad in the feed. All posts containers look similar, the only difference is the "sponsorized" tag which is the height child of the main container.

script.js:

var x = document.getElementsByClassName("uiStreamSponsoredLink").parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
x.className += "otherclass";

Manifest:

{
  "name": "Project",
  "version": "0.0.1",
  "manifest_version": 2,
  "default_locale": "en",
  "icons": {
    "16": "img/icon16.png",
    "48": "img/icon48.png",
    "128": "img/icon128.png"
  },
  "permissions": [
    "*://*.facebook.com/*"
  ],
  "content_scripts": [
    {
      "matches": [
        "*://*.facebook.com/*"
      ],
      "css": [
        "content_script/replace-reactions.css"
      ],
      "js": [
        "content_script/script.js"
      ]
    }
  ],
  "web_accessible_resources": [
    "img/*.png"
  ]
}
nico_lrx
  • 715
  • 1
  • 19
  • 36
  • You should start by checking the browser console for errors. `document.getElementsByClassName("uiStreamSponsoredLink").parentNode` for example is definitively wrong, because getElementsByClassName returns a NodeList, so you need to access the items on that list individually. – CBroe Nov 04 '16 at 11:28
  • You mean by doing a foreach? The problem is that facebook updates the html when you scroll – nico_lrx Nov 04 '16 at 11:34

1 Answers1

0

In script.js add this,

For example,

document.getElementsByTagName('body').attr('class','YOUR CLASS NAME');

Here I set class name for body tag. You can set this for any element in the page.

Subin Vs
  • 111
  • 1
  • 12
  • But I want to only point elements that contain an add in the Facebook feed. I guess I have to find this element and add a specific class for that, isn't it? – nico_lrx Nov 04 '16 at 10:36
  • 1
    This is a bit after the question was asked but if you will do what the answer says you will delete the other classes on that element. It is better to use classList. See [this answer](https://stackoverflow.com/a/196038/463464) and this [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). – Randall Flagg Dec 09 '18 at 09:11