Open In App

p5.js select() Function

The select() function is used to search an element in the page with the given id, class or tag name and return it as a p5.element. It has a syntax similar to the CSS selector. An optional parameter is available that can be used to search within a given element. This method only returns the first element if multiple elements exist on the page that matches the selector.

Note: The DOM node of the element can be accessed using the .elt property.



Syntax:

select(name, [container])

Parameters: This function accept two parameters as mentioned above and described below:



Return Value: When the given element is successfully found, it returns a p5.element that contains the node. Otherwise, it returns null.

Below examples illustrates the select() function in p5.js:

Example 1:




function setup() {
  createCanvas(650, 50);
  textSize(20);
  text("Click the mouse to select the paragraph" +
       " element and change its position.", 0, 20);
   
  para1 = createP("This is paragraph 1");
  para2 = createP("This is paragraph 2");
  para3 = createP("This is paragraph 3");
}
   
function mouseClicked() {
  
  // Select the first
  // paragraph element
  selectedP = select("p");
   
  // Change position to 200, 20
  selectedP.position(200, 20);
}

Output:

Example 2:




function setup() {
  createCanvas(650, 300);
  textSize(20);
  text("Click the mouse once to select the"+
       " canvas and change its color.", 0, 20);
   
}
   
function mouseClicked() {
  
  // Select the first
  // canvas element
  selectedCanvas = select("canvas");
   
  // Get the DOM node using .elt and
  // change background color to green
  selectedCanvas.elt.style.backgroundColor
        = "green";
}

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/select


Article Tags :