0

I'm writing a Chrome plugin to modify the Facebook homepage.

How would I add an extra <li> to the <ul> with a class of _54nf?

Here's my current code:

function addLabel()
{
var ul = document.getElementsByClassName("_54nf");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Test"));
ul.appendChild(li); // line 6
}

addLabel();

The error I'm getting is:

Uncaught TypeError: undefined is not a function

I presume the problem is getElementsByClassName but I'm not sure.

Sebastian
  • 3,548
  • 18
  • 60
  • 95

1 Answers1

2

getElementsByClassName returns a list of nodes (notice the plural s). Use:

var ul = document.getElementsByClassName("_54nf")[0];

to index down to just the first one.

This assumes there's only one such element on the page, or you only want to modify the first one.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Or... `document.querySelector("._54nf")` – cookie monster Jul 02 '14 at 20:36
  • @Barmar Thanks for your reply. When I try this I'm getting the error `Uncaught TypeError: Cannot read property 'appendChild' of undefined` on line 6. Any idea what's wrong? – Sebastian Jul 02 '14 at 20:37
  • That means that `getElementsByClassName` isn't finding anything that matches the class you gave. Are you sure you got the class name right? Does this class always exist? If not, you need to test `ul.length` before trying to use it. – Barmar Jul 02 '14 at 20:41
  • Yep, if you search the source of the Facebook homepage there's a ` – Sebastian Jul 02 '14 at 20:43