p5.Element addClass() Method

The addClass() method of p5.Element in p5.js is used to add the specified class to an element. An element can have multiple classes assigned to it. Also, one class can be specified to multiple elements on the page.
Syntax:
addClass(class)
Parameters: This function accepts a single parameter as mentioned above and described below.
- class: It is a string that denotes the class to be added.
Example: The example below illustrates the addClass() method in p5.js.
Javascript
function setup() {Â Â createCanvas(550, 300);Â Â textSize(18);Â
  text("Click on the buttons to add the given " +       "class to the element", 20, 20);Â
  setBtn =     createButton("Add given class to element");  setBtn.position(30, 40);  setBtn.mouseClicked(addNewClass);Â
  setBtn =     createButton("Show current classes");  setBtn.position(300, 40);  setBtn.mouseClicked(showClasses);Â
  class_name = createInput('class1');  class_name.position(30, 80);Â
  // Create a new p5.Element  tmpElement = createElement("div");}Â
function addNewClass() {Â Â clear();Â
  // Get the class to set  let classToSet = class_name.value();Â
  // Set the class of the element  tmpElement.addClass(classToSet);Â
  text("Class added with name: " +        classToSet, 30, 120);Â
  text("Click on the button to add the given " +       "class 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 to the element", 20, 20);} |
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.zambiatek.com/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5.Element/addClass
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek 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!



