Saturday, August 30, 2025
HomeLanguagesJavascriptp5.js select() Function

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:

  • name: It is a string which denotes the id, class or tag name of the element that has to be searched.
  • container: It is an optional parameter which denotes an element to search.

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/

Reference: https://p5js.org/reference/#/p5/select

RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7012 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS