What are the best practices for managing DOM manipulation with TypeScript instead of plain JavaScript?

I'm a beginner in Typescript and I want to incorporate the following JavaScript functionality into a Typescript file.

http://jsfiddle.net/SgyEW/10/

$('.toggler').live('click', function() {

            var idname = $(this).attr('name');

            $('.content').hide();
            $('#' + idname).show();
        });
#box {
            border: 1px solid gray;
            background-color: #f3f3f3;
            -webkit-transition: all 1s linear;
        }
        .content {display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
        <div>
            <button class="toggler" name="content1">content 1</button>
            <button class="toggler" name="content2">content 2</button>
            <button class="toggler" name="content3">content 3</button>
        </div>

        <div id="box">
            <div id="content1" class="content">
                Cras dictum. Maecenas ut turpis. In vitae erat ac orci dignissim eleifend. Nunc quis justo.
            </div>
            <div id="content3" class="content">
                Cras dictum. Maecenas ut turpis....consectetuer.
            </div>
            <div id="content2" class="content">
                 Cras dictum. Maecenas ut...
                Cras ultricies placerat eros. Quisque odio eros, feugiat non, iaculis nec, lobortis sed, arcu. Pellentesque....
            </div>

When toggling the button, I would like certain elements to appear or disappear accordingly. My main question is how to achieve this kind of JavaScript behavior with Typescript? I've searched extensively but haven't found a clear answer yet. So... What's the best approach, importing a JavaScript file into Typescript or implementing the function directly as Typescript? Also, are there any examples of DOM manipulation with Typescript?

Answer №1

TypeScript is essentially JavaScript with added type safety features. If you are looking to convert your jQuery code into TypeScript, all you need to do is incorporate the typings for jQuery:

Learn how to use jQuery with TypeScript here

For more information on types in TypeScript, you can refer to the following links:

Understanding the difference between *.d.ts and *.ts files in TypeScript

Note:

If you wish to achieve the functionality below using vanilla JavaScript instead of jQuery:

$('.toggler').live('click', function() {

  var idname = $(this).attr('name');

  $('.content').hide();
  $('#' + idname).show();
});

You can make the transition as shown here:

let element = document.getElementByClassName('toggler')[0]

element.addEventListener('click', () => 
{
  let idname = element.getAttribute('name');

  document.getElementByClassName('content')[0].style.display = 'none';
  document.getElementById(idname).style.display = 'block';
});

This code snippet should provide similar functionality without relying on jQuery.

For those working with Angular, it's recommended to utilize @ViewChild() for DOM manipulations:

Read more about @ViewChild() here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The left side inputs are contingent upon the div

I am faced with a challenge involving two inputs inside a div. Below is the code snippet: <div style="width:100%;height:500px;border-style:solid;border-color:#1d69b4;margin-top:25px;"> <div style="float:left; width:70%;height:100 ...

Tips for incorporating a JavaScript variable into the value parameter of an HTML checkbox:

Within my document, I have a JavaScript variable named 'testJava' <script> var testJava = 'script Test'; </script> Located at the bottom of the page is a checkbox. I am looking to append the 'testJava' variable t ...

Sorting options tailored for arrays within arrays

Here is an array with nested arrays: var array = [ ['201', 'Tom', 'EES', 'California'], ['189', 'Charlie', 'EE', 'New Jersey'], ['245', 'Lisa', ' ...

A guide on successfully handling errors while utilizing S3.getsignedurlpromise() in node.js

I am faced with a challenge in my project involving a node.js server that downloads images from an s3 bucket and serves them to a React client. The issue arises when the wrong file key is sent to the S3 client, as I want to handle this error gracefully by ...

Is there a way for me to generate an Nx command that can dynamically create a library with a specified name?

In the world of Nx and Angular, I have a repository named org housing all my projects. To create a special library within this setup, like one called auth, I typically use a command that looks like this: npx nx g @nx/angular:lib auth-data-access --directo ...

Guide to activating the 'Next' button on WP Forms using JavaScript code when certain conditions are fulfilled

Is there a way to adjust the JavaScript code provided so that the visibility of the "Next" button is dependent on whether at least one item in the 'wpforms-icon-choices-item' class has the '.wpform-selected' class on the current page or ...

How to Utilize Vue and Checkboxes for Filtering a List?

My current challenge involves filtering a list of posts based on userId using checkboxes. The data is being retrieved from: https://jsonplaceholder.typicode.com/posts. I aim to include checkboxes that, when selected, will filter the list by userId. Here is ...

Condense styles and templates into inline format using Angular-cli

Can anyone help me with configuring angular-cli to support inlining of css and html resources during the build process? I am currently using angular-cli version 1.0.0-beta.24. I attempted building with both ng buld and ng build --env=prod --target=product ...

Retrieving Names Using Angular2 Dynamic Component Loader to Render a Component List

I am currently utilizing a Dynamic Component Loader to present a series of components using *ngFor: <div [dragula]='"bag-one"' [dragulaModel]='types'> <div *ngFor="let component of types; let i = index"> <dcl-wrapp ...

Send users from the web (using JavaScript) to the Windows Phone app, and if the app is not installed, direct them

In the following code snippet, I am using angular.js to detect the mobile platform and redirect to the native app. If the app is not installed, it will redirect to the market: $scope.isMobile = { Android: function() { return navigator.userAgent.ma ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

Creating a function in Typescript that transforms an array into a typed object

Recently, I have started learning TypeScript and I am working on a function to convert arrays from a web request response into objects. I have successfully written the function along with a passing unit test: import { parseDataToObject } from './Parse ...

Navigating in an Electron app using Angular

It appears that I am encountering difficulties with routing pages in my angular electron desktop application. Despite configuring the routing similar to an angular app, nothing seems to be functioning properly. I have specified router links such as "/hom ...

The JSON data fails to load upon the initial page load

I am having trouble getting JSON data to display in JavaScript. Currently, the data only shows up after I refresh the page. Below is the code I am using: $(document).ready(function () { $.ajax({ url:"http://192.168.0.105/stratagic-json/pr ...

Exploring ways to reach a specific digit level in JavaScript

As a newcomer to JavaScript, I've been searching online and trying different solutions but none have worked for me. Currently, I have a variable called num = 71.666666666 I'm looking to limit this number to 71.66 So far, I have attempted the f ...

To verify if the given input value matches any of the options, then mark the checkbox

My script is functional, but I believe there's a more efficient way to handle it using an if statement. However, I've been unsuccessful in getting it to work. I am attempting to create a search function that checks if the value is 2, 3, or 5. If ...

Using Jquery for Animation: Tips on Revealing Text After Changing Element Color or Styles

Hey everyone, I ran into a bit of trouble while working with jQuery and trying out some animations. My goal was to make a textbox appear and display text when a button is highlighted, similar to a gallery setup. However, I managed to get halfway through th ...

What is the best approach for managing multiple post requests in Angular?

Currently, in my Angular 12 and NestJS project, I am facing a challenge where I need to synchronize approximately 3000 items from an external API into my application's database. However, during the process of submitting the request, I encounter variou ...

Potential issue with Angular material autocomplete not displaying suggestions when using input.setValue()

After clicking on the input element, the autocomplete options are displayed. However, if I dynamically modify the input element's value, the autocomplete options do not appear. <mat-form-field> <input type="text" [formControl]="d ...

I'm looking to develop a custom CKEditor plug-in that will allow users to easily drag and drop elements within the editor interface

Upon observing that dragging and dropping text or images within a CKEditor editor instance does not trigger the "change" event, I devised a temporary solution by implementing code triggered by the "dragend" event. However, my ultimate goal is to create a C ...