Thursday, September 4, 2025
HomeLanguagesJavascriptp5.Element class() Method

p5.Element class() Method

The class() method of p5.Element in p5.js is used to set or return the classes of the element. When no class is specified as a parameter, it returns the current classes of the element. An element can have multiple classes assigned to it. Also, one class can be specified to multiple elements on the page.

Syntax:

class(class)

Parameters: This function accepts a single parameter as mentioned above and described below

  • class: It is a string that denotes the class of the element.

Example: The example below illustrates the class() method in p5.js.

Javascript




function setup() {
  createCanvas(550, 300);
  textSize(18);
  
  text("Click on the button to add the given " +
       "class(es) to the element", 20, 20);
  
  setBtn = 
    createButton("Create new Element with given classes");
  setBtn.position(30, 40);
  setBtn.mouseClicked(createNewElement);
  
  setBtn = 
    createButton("Show Last Element class");
  setBtn.position(300, 40);
  setBtn.mouseClicked(showClasses);
  
  class_name = createInput('tmpClass');
  class_name.position(30, 80);
}
  
function createNewElement() {
  clear();
  
  // Create a new p5.Element
  tmpElement = createElement("div");
  
  // Get the class to set
  let classToSet = class_name.value();
  
  // Set the class of the element
  tmpElement.class(classToSet);
  
  text("Class set with the names: " +
       classToSet, 30, 120);
  
  text("Click on the button to add the given " +
       "class(es) to the element", 20, 20);
}
  
function showClasses() {
  clear();
  
  // Get the classes of the element
  let setClasses = tmpElement.class();
  
  // Display the classes
  text("The classes of the element are: " +
       setClasses, 30, 120);
  
  text("Click on the button to add the given " +
       "class(es) to the element", 20, 20);
}


Output:

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5.Element/class

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS