Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

p5.js | select() Function

  • Last Updated : 29 Jan, 2020

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.


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);
  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);


Example 2:

function setup() {
  createCanvas(650, 300);
  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
        = "green";


Online editor:

Environment Setup:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!