Nyx

Chapter 2 · Basics

Finding elements

Before Nyx can change anything on a page, you have to tell it which part of the page you mean. In this chapter you'll learn every common way to find elements, how to check what you found, and how to pick just one of them.

What "finding" means

Think of a classroom. A teacher can call out to students in different ways:

"Asha, please stand up."One student, by name. In Nyx this is an id.
"Blue team, stand up."A group that shares a label. In Nyx this is a class.
"Everyone, stand up."Everyone of one kind. In Nyx this is a tag.

The text you put inside nyx("...") is called a selector. It describes which elements you want. Nyx looks through the page and collects every element that matches.

Good news if you know CSS

Nyx selectors are exactly the same as CSS selectors. If you've written .card { color: red; } in a stylesheet, you already know how to write nyx(".card").

Find one element by its id

An id is a unique name for one element. To find it, write # followed by the id.

HTML

<h3 id="greeting">Good morning</h3>

Nyx

nyx("#greeting")

Read #greeting out loud as "the element whose id is greeting". The # is not part of the id; it only tells Nyx "this is an id".

Good morning

Today is a school day.

Now change #greeting to #today and run it again. Which line changed?

Find a group by its class

A class is a label that many elements can share. To find them, write a dot followed by the class name. Nyx finds all of them, and whatever you do next happens to every one.

HTML

<li class="done">Maths</li>
<li>Science</li>
<li class="done">English</li>

Nyx

nyx(".done")

Finds Maths and English, but not Science.

Homework this week:

  • Maths
  • Science
  • English
  • History

One line crossed out two items. You never have to write a loop to change a whole group.

An element can have several classes

<li class="done urgent"> has two classes, separated by a space. Both nyx(".done") and nyx(".urgent") will find it.

Find every element of one kind

Write a tag name with no symbol in front to find every element of that kind: nyx("p") for paragraphs, nyx("button") for buttons, nyx("img") for images.

Class rules

Be on time.

Bring your notebook.

Try nyx("button") or nyx("h3") instead of nyx("p").

Be careful with tags on a real page

nyx("p") finds every paragraph on the whole page, including ones you forgot about. Tags are fine for small pages; on bigger pages, a class is usually safer. (On this site, each example only searches inside its own box.)

The three basic selectors side by side

You writeNyx finds
nyx("#menu")The one element with id="menu".
nyx(".card")Every element with class="card".
nyx("button")Every <button> element.

Find elements inside other elements

Put a space between two selectors to mean "inside". Read it from right to left: "#menu a" means "links that are inside #menu".

#menuLook inside this  A space aFind these

This is useful when the same kind of element appears in several places. Here, only the links in the menu should turn bold:

Read the school rules before you join.

Change it to nyx("a") and run it. Now the link in the paragraph turns bold too.

Another way: tell Nyx where to look

You can also pass a second value to nyx(): where to search. These two lines find exactly the same elements:

nyx("#menu a");
nyx("a", "#menu");   // find "a", but only inside #menu

Use whichever you find easier to read.

Find by an attribute

An attribute is any extra setting written inside a tag, like name="email" or type="checkbox". Put it in square brackets to find elements by it. This is handy for form fields, which often have a name but no id or class.

You writeNyx finds
nyx("[name=email]")The element with name="email".
nyx("[type=checkbox]")Every checkbox.
nyx("input[required]")Every <input> that has the required attribute.

.value() fills in a form field. You'll learn more about it in the next chapter.

How many did I find?

A search can find zero, one or many elements. Two methods tell you what you got:

.count()A number: how many elements were found.
.exists()true if at least one was found, false if none.

To see the answers, we'll use print(), which shows values in the Output box. Remember, it only works on this website; on your own page, use console.log(). (See Getting started for how print() works.)

  • Asha
  • Ravi
  • Meera
  • John

.exists() is most useful with if, to run code only when something is on the page:

if (nyx("#cookie-banner").exists()) {
  nyx("#cookie-banner").show();
}

Picking just one

Sometimes you find many elements but only want one of them.

.first()Just the first one.
.last()Just the last one.
.eq(n)The one at position n. Counting starts at 0.

Counting starts at 0

This surprises everyone at first. In JavaScript, the first item is number 0, the second is number 1, and so on.

ItemPosition
1st: Gold.eq(0), the same as .first()
2nd: Silver.eq(1)
3rd: Bronze.eq(2)
Last.eq(-1), the same as .last(). Negative numbers count from the end.
  1. Gold: Asha
  2. Silver: Ravi
  3. Bronze: Meera

Add a line that colours Bronze. Try it with .eq(2), then with .last().

Doing something to each one

Most methods, like .text() or .css(), already change every element you found. But sometimes each element needs something different, like its own number. For that, use .each().

nyx(".student").each((item, i) => {
  item.text((i + 1) + ". " + item.text());
});
  1. nyx(".student")Find every element with the class student.
  2. .each(...)Run the function below once for every element found.
  3. (item, i) => { ... }Each time, item is the current element (ready to use with Nyx methods) and i is its position, starting at 0.
  4. item.text((i + 1) + ". " + item.text())Put a number in front of the text. We use i + 1 so the list starts at 1, not 0.
  • Asha
  • Ravi
  • Meera

You can call the two names anything you like. (student, number) works just as well.

Common mistakes

When a selector finds nothing, your code does nothing. These are the usual reasons:

MistakeFix
nyx("title")Forgot the symbol, so Nyx looked for a <title> tag. Write nyx("#title").
nyx("#card")Used # for a class. If the HTML says class="card", write nyx(".card").
nyx("#Title")Wrong capital letter. Names are case-sensitive: Title and title are different.
nyx("# title")Extra space. Write #title with no gap.
nyx(#title)Missing quotes. A selector is a string, so it always needs quotes.

Nyx spots most of these and tells you the fix. Run this example and read the Output, then try the other two lines:

Exam on Friday

Bring two pencils.

To try a line that starts with //, delete the //. Two slashes turn a line into a note that the browser ignores.

Good to know

nyx() can do a few more things that you'll meet in later chapters:

nyx("h1, h2")A comma means "and also": every <h1> and every <h2>.
nyx("<li>New</li>")When the text starts with <, Nyx makes a brand-new element instead of searching. See Changing content.
nyx(this)Wraps an element you already have so you can use Nyx methods on it. See Events.
.get()The plain browser element, for code written without Nyx.

Exercise

Fill in the blanks, then press Check answers.

1. Find the element with the id score.

nyx("score").text("10");

2. Find every element with the class student.

nyx("").show();

3. Find every link (<a>) inside the element with id footer.

nyx("#footer ").hide();

4. Show how many .card elements are on the page.

console.log(nyx(".card").());

5. Pick the third .photo.

nyx(".photo").eq().show();

6. Pick the last .message.

nyx(".message").().hide();

Remember

#name finds by id, .name finds by class, a plain word finds by tag.
A space means "inside": "#menu a" is the links inside #menu.
Square brackets find by attribute: "[name=email]".
Methods change every element found, no loop needed.
.count() and .exists() tell you what was found.
.first(), .last() and .eq(n) pick one. Counting starts at 0.
.each((item, i) => { ... }) runs code for each element separately.