Skip to content
Related Articles

Related Articles

Improve Article

p5.js Element hasClass() Method

  • Last Updated : 20 Nov, 2020

The hasClass() method of p5.Element in p5.js is used to check if the specified class is already present in the element. It returns a boolean value denoting if the class was present or not. An element can have multiple classes assigned to it.


hasClass( 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 checked.

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

    <script src=
    <script src="sketch.js"></script>

Javascript code: The following code is used for the above “sketch.js” file.


function setup() {
  createCanvas(600, 300);
  // Create a new p5.Element
  tmpElement = createElement("div");
  text("Click on the buttons to add, remove " +
       "or check the class of the element", 20, 20);
  setBtn = 
    createButton("Add color class to element");
    setBtn.position(30, 40);
    setBtn.mouseClicked(() => {
  removeBtn =
    createButton("Remove color class from element");
  removeBtn.position(30, 80);
  removeBtn.mouseClicked(() => {
  showBtn = createButton("Check if class exists");
  showBtn.position(30, 120);
function checkClass() {
  // Check if the given class exists
  let hasC = tmpElement.hasClass("color");
  text("hasClass('color') gives the output: " +
       hasC, 20, 180);
  text("Click on the buttons to add, remove or " +
       "check the class of the element", 20, 20);


Online editor:
Environment Setup:

My Personal Notes arrow_drop_up
Recommended Articles
Page :