Common JavaScript Built-in Functions Explained
JavaScript has many built-in functions that help with selecting, modifying content and performing calculations. Here are some examples of such built-in functions.
DOM Manipulation Functions
- getElementById(id) β Selects a single HTML element by its id. This is one of the most common ways to interact with elements in the DOM.
- getElementsByClassName(className) β Selects all elements that have the specified class name(s). Returns an HTMLCollection.
- getElementsByTagName(tagName) β Returns all elements in the document that match a specific tag name (e.g., div, p).
- querySelector(selector) β Selects the first element that matches a given CSS selector.
- createElement(tagName) β Creates a new HTML element dynamically using JavaScript.
Number Parsing Functions
- parseInt(string) β Converts a string into an integer (whole number).
- parseFloat(string) β Converts a string into a floating-point number (decimal).
Function Binding and Array Methods
- bind() β Creates a new function that remembers a specific context, similar to putting a sticky note on a function to remind it of a specific this value.
- push(value) β Adds an item to the end of an array.
- pop() β Removes the last item from an array.
- sort() β Sorts an array in ascending or descending order.
- shift() β Removes the first item from an array.
- unshift(value) β Adds an item to the beginning of an array.
Math Functions
- Math.abs(number) β Converts a number to its absolute (positive) value.
- Math() β A built-in JavaScript object that provides various mathematical functions and constants.
Other Useful Functions
- getRootNode() β Retrieves the root (top-most) element in the DOM tree.
- console.error(message) β Displays an error message in the browserβs developer console.
- addEventListener(event, function) β Listens for a specific event (like a click) on a webpage and executes a function when the event occurs.
- eval(string) β Executes JavaScript code written inside a string (Use with caution due to security risks).
- escape(string) β Encodes a string for safe transfer over the internet.
- document.write(content) β Writes content directly onto a webpage (Not recommended for modern web development).
- length β Returns the number of elements in an array or the number of characters in a string
Top comments (0)