NUS Hackers Wiki
NUS Hackers Wiki
  • NUS Hackers Wiki
  • Hackerschool
    • Virtual Machines and Linux
    • Beginners' Guide to the Terminal
      • Introduction to the Terminal
      • Modern Shell Tools
      • Shell Scripting
      • Real World Scripting
      • Resources
    • Self-Hosting: Three Easy Pieces
      • 1. Setting up your server
      • 2. Running Services
      • 3. Monitoring your server
    • Vim
    • Introduction to Zig
      • Language Basics
      • Error Handling
      • Memory Management
      • Working with C
      • Exploring comptime
    • CI/CD with Github Actions
      • Background
      • Basics of Github Actions
        • Target workflow
        • Running unit tests
        • Linting code
        • Deploying to Github Pages
      • Advanced use cases
        • Pollers
        • Github script
        • Executing third-party scripts
        • Reusable workflows
      • Cookbook
    • Lightning Git
      • Git Concepts
      • Getting Started with Git
      • Making your first commit
      • Branching
      • Merge Conflicts
      • Integrating remote repositories
      • Collaborative Workflows
      • Commit Manipulation and Reflog
      • Interactive rebasing
      • filter-repo
  • Orbital
    • JavaScript
      • Browser Developer Tools
      • Getting Started
      • Datatypes
      • Operators and Operations
      • Loops and Conditions
      • Functions
      • Strings
      • Arrays
      • HTML
        • Getting Started
        • Tag Attributes
        • HTML Forms
        • Browser Inspector
      • CSS
        • Selectors
        • Colors in CSS
        • Measurements in CSS
        • The Box Model
        • Adding Styles - Part 1
        • Adding Styles - Part 2
      • Working with the DOM
        • Querying the DOM - Selectors
        • Querying the DOM - Element Attributes
        • Querying the DOM - Element Styles
        • Events with JS and HTML
        • Exercise: Click Counter
        • Editing the DOM
        • Fetch Requests
        • Exercise: The NUSMods API
    • React
      • Setup
      • State
    • React Native
      • Setup
      • Intro to JSX
      • Basic Syntax
      • Handling UI
      • Props
      • State Management
    • Git
      • Setup
      • Command Glossary
      • Fundamental Concepts
        • Getting Started
        • Integrating Remote Repositories
        • Branching
        • Merge Conflicts
      • Collaborative Workflows
        • Fork and PR Workflow
        • Branch and PR Workflow
      • Advanced Concepts
        • Ignoring Files
        • Commit Message Conventions
        • Github Collaborators
        • CI/CD with Github Actions
        • Advanced Git Commands
      • FAQ
    • Telegram Bot
      • Creating a TeleBot
      • API Calls
      • Telebot Basics
      • Integrating API's
    • Relational Database
      • Database Overview
      • Database Design
      • Entity Relationship Diagram
      • SQL Basics & PostgreSQL
    • TypeScript
      • Types and Interfaces
      • Utility Types
      • Typing Component Props, Events, and Hooks
      • Why You Should Avoid Using any (and What to Do Instead)
      • TypeScript Tricks You’ll Use All the Time in React
Powered by GitBook
On this page
  • Pick an element
  • Check its attributes
  • In general...
  • Changing its attributes
  • Changing the class
  • Hiding the button
  • In general...
  • Contents of an element
  • Next steps
Edit on GitHub
Export as PDF
  1. Orbital
  2. JavaScript
  3. Working with the DOM

Querying the DOM - Element Attributes

PreviousQuerying the DOM - SelectorsNextQuerying the DOM - Element Styles

Last updated 12 months ago

Open up the html page you made . Open it in the browser, and open the browser console. We're going to query the document for elements and change their attributes, then see the changes in real-time.

Pick an element

Our page currently only has two things: a heading and a button. So lets pick one of them. Run the following in the console:

let button = document.querySelector("button");

Now, button has the button element assigned to it. Test it by typing button and hitting enter in the console; you should see something like below:

Check its attributes

To get an element's properties or attributes, we can use dot notation:

button.onclick; // function onclick(event)

The above line returns the value of the onclick attribute, which is a function. To make things more interesing, let's go to the html file and add an id attribute:

<button onclick="alert('Hello!')" id="hello">Say hello</button>

Reload the page, reopen the console and rerun the above lines to select the button (this time try using the id as a selector instead).

Then run:

button.id; // "hello"

This should return "hello", since that is the id we assigned the button.

In general...

Given that you have a variable element that has been assigned an element after querying the DOM, you can access any of its attributes using dot notation:

element.attributeName; // returns attribute value

If the element has not been assigned a given attribute it returns an empty string, or if the attribute is invalid it returns undefined

Example: running the following should return "" since the button has no class:

// the class attribute uses .className, not .class
button.className; // ""
button.class; // undefined

Some attributes have default values, such as the hidden attribute which is false by default:

button.hidden; // false

Changing its attributes

Just as an element's attributes can be accessed by JS code, they can also be changed by reassigning them values. Let's try this on our button.

Changing the class

Run the following (after querying for the button if needed):

button.className = "random-class"; // feel free to plug in your class name

You won't see any visual change on the page (since the class doesn't affect its appearance) but if you navigate to the Browser Inspector and look for the button, you'll see that it has been assigned a class attribute. You can even remove the attribute if you wish:

button.className = "";

To visualise the change in a better way, try these steps:

  1. Go to your CSS file and add some rules for a class "random-class" (or whatever you want to call it)

  2. Refresh the page, reopen the console, and query for the button

  3. Assign the button a class attribute as above, with the class being "random-class" (or whatever you called it)

  4. You'll see the CSS being applied to the button

  5. Reset the class attribute back to blank. You'll see that the styling no longer applies.

Hiding the button

To hide the button (or any element really) just set its hidden attribute to true:

button.hidden = true;

You'll see the button disappear from the page. To make it reappear, set the hidden attribute back to false:

button.hidden = false;

In general...

Any element's (valid) attributes can be assigned or reassigned to any (valid) value by accessing them using dot notation after querying for the element. If an invalid attribute or invalid value is assigned, then it is simply ignored by the page.

If there is no match for the element query, null is returned by the querySelector and getElementById functions. this means that trying to get/reassign any attributes will cause an Uncaught TypeError: x is null.

Contents of an element

There are two ways to get the content of an element. One is to use to .innerHTML property:

button.innerHTML; // "Say Hello"

And the other is to use the .innerText property

button.innerText; // "Say Hello"

The difference between the two is that innerHTML refers to everything inside the element, whereas innerText refers to just the text inside the element. In our example there is no difference, but let's try editing our html file temporarily:

<button onclick="alert('Hello!')" id="hello">
    <span>Say hello</span>
</button>

Now we have a <span> element inside the button; a <span> is just an easy way of encapsulating part of a line so specific styling can be added to it.

Now try getting the contents:

let button = document.getElementById("hello");
button.innerHTML; // "<span>Say Hello</span>" with some whitespace around it
button.innerText; // "Say Hello"

You can change the contents as well by reassigning the properties.

Next steps

Next, we'll look at how you can modify the style of an element using JS.

earlier