Open In App

p5.js Element hasClass() Method

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.

Syntax:



hasClass( class )

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

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






<html>
  
<head>
    <script src=
    </script>
    <script src="sketch.js"></script>
</head>
  
<body></body>
  
</html>

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




function setup() {
  createCanvas(600, 300);
  textSize(18);
    
  // 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(() => {
    tmpElement.addClass("color");
  });
  
  removeBtn =
    createButton("Remove color class from element");
  removeBtn.position(30, 80);
  removeBtn.mouseClicked(() => {
    tmpElement.removeClass("color");
  });
  
  showBtn = createButton("Check if class exists");
  showBtn.position(30, 120);
  showBtn.mouseClicked(checkClass);
}
  
function checkClass() {
  clear();
  // 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);
}

Output:

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


Article Tags :