How to Pass Over an Element Using TypeScript and jQuery ?
Last Updated :
24 Apr, 2025
This article will show how we can pass an HTML element to a function using jQuery and TypeScript together. There are different ways available in which we can pass an element to a function using TypeScript and jQuery as listed below.
Before moving on to the implementation, make sure that you have jQuery installed in your project environment. Use the below commands to install and use jQuery.
npm commands to install jQuery:
npm install jquery
npm install --save-dev @types/jquery
Once jQuery gets installed in your project use the below command to import and use it in your TypeScript file.
import variable_name_by_which_you_want_to_import_jQuery from 'jquery'
Using HTMLElement as the passing element type
In this approach, we will assign the HTMLElement type to the parameter while declaring the function and then use it as an element inside that function.
Syntax:
function funcName(paramName: HTMLElement){
// Function statements
}
funcName(selectedElement[0]);
Example: The below code example passes the element as an HTMLElement type to the function and uses it as an element inside it.
JavaScript
// index.ts file
import $ from "jquery";
declare var global: any;
global.jQuery = $;
import "jquery-ui";
const changeText = (passedElement: HTMLElement) => {
$(passedElement).text(`
The text has been changed by passing
element to function using the TypeScript
and jQuery.
`);
}
$('#btn').on('click', function () {
const selectedElement = $('#result')[0];
changeText(selectedElement);
})
HTML
<!-- index.html file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width,
initial-scale=1.0" />
<title>Document</title>
<style>
.h1 {
font-size: 30px;
color: green;
}
#result {
color: #FF671F;
}
</style>
</head>
<body>
<center>
<h1 class="h1">
GeeksforGeeks
</h1>
<h3 id="result">
Click the below button
to change the this text.
</h3>
<button id="btn">
Change Text
</button>
</center>
</body>
</html>