A user-friendly JavaScript framework focused on manipulating the DOM using a module approach and aiming to mirror the ease of use found in jQuery

This is simply a training exercise. I have created a script for solving this using the resource

    (function(window) {
    function smp(selector) {
    return new smpObj(selector);
    }

    function smpObj(selector) {
        this.length = 0;
        if (!selector ) {
            this.el = [];
            return this;
            }
        if (selector.nodeType ) {
            this.el = selector;
            this.length = 1;
            return this;
        } else if(selector[0]==='#'){
            this.el = document.getElementById(selector.slice(1, selector.length));
            this.length = 1;
            return this;
        } else if(selector[0]==='.'){
            this.el = document.getElementsByClassName(selector.slice(1, selector.length));
            this.lenghth=this.el.length
            return this;
        }
        else return null;
    }
 })(window);

I then attempted to call it like this:

smp('body');

However, the browser was unable to find my smp definition.
In the future, I plan to add methods to use it in this way (for example, changing color):

 smp('.myClass').method('attr')

I would greatly appreciate it if someone could point out my mistake.

Update: I am still facing issues with adding methods like:

  smp('.myClass').method('attr') 

I attempted to do it like this:

  (function color(smp) {
    window.smp.prototype.changeColor = function() {
        for (var i = 0; i < this.length; i++) 
            this.el[i].style.color = color;
        return this;
    };
})(smp);

Answer №1

The tutorial you referenced has a helpful explanation in the Module Export section.

To utilize the function effectively, it must be assigned to a variable, whether globally or locally. One way to do this locally is:

var smp = (...)(window)

This approach requires that something be returned in the function. Hence, before the })(window) part of your code, ensure to return the smp function.

return smpSelector

Combining all steps together:

var smp = (function(window) {

    function smpSelector(selector) {
      // ... snip
    }

    function smpObj(selector) {
      // ... snip
    }

    return smpSelector;

 })(window);

Moreover, if you wish to keep this functionality in a separate file while still maintaining access to smp, you can assign it globally. This is commonly practiced in various libraries, such as jQuery:

(function(window) {

    function smpSelector(selector) {
      // ... snip
    }

    function smpObj(selector) {
      // ... snip
    }

    window.smp = smpSelector

 })(window);

Subsequently, from a different file, execute the following:

 <script src="/path/to/smp/file"></script>
 var foo = smp('something')

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

How can I correctly focus on 'highlight' events using the tab key on an HTML element?

I'm struggling to figure out the event that is triggered when an element gains focus through tab navigation. I want all buttons in the codepen provided to expand to full size when tabbed over. https://codepen.io/anon/pen/YopBaz Currently, I have achi ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

Bring in a collection of classes of various types from one TypeScript file to another

In my code file exampleA.ts, I define an object as follows: import { ExampleClass } from 'example.ts'; export const dynamicImportations = { ExampleClass }; Later, in another file named exampleB.ts, I import an array that includes class types and ...

What are the steps to create a connect4 board featuring rounded corners and curved sides?

How can I create a Connect4 board with the exact styles and properties shown in the image? I want to achieve the curved sides effect as displayed. Can this be done using only HTML elements, or is there an easy SVG solution available? Here is my current co ...

Obtain a specific element in Puppeteer JS by utilizing the waitForSelector function to detect when its class name changes

I am faced with a situation where I need to wait for a specific element to change its classes dynamically. The challenge arises when utilizing the waitForSelector function, as it fails to work when no new element is added to the DOM. Instead, it is the &l ...

Is it possible to trigger a textbox text change event after autocompleting using jQuery

I recently implemented a jquery autocomplete plugin for a textbox: $('#TargetArea').autocomplete({ source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })' }); The implementation is working as expected. ...

Unable to retrieve data in Node Express after querying completion

I created a basic custom module that is intended to return database records from its methods. After executing a query, I can retrieve all the records but when attempting to assign them to a variable, it shows as null. I'm unsure of what's causin ...

Watch for changes in a nested collection in Angular using $scope.$watch

Within my Angular application, there is a checkbox list that is dynamically generated using nested ng-repeat loops. Here is an example of the code: <div ng-repeat="type in boundaryPartners"> <div class="row"> <div class="col-xs- ...

Tips for organizing a grid to achieve the desired layout

Overview I am working on organizing items within the MUI Grid. The grid consists of multiple dynamic rows and columns. Each row has a fixed first column, followed by a variable number of scrollable columns. The scrollable columns should be grouped togethe ...

Troubleshooting CSS Problems: Issues with background repeating and footer placement

I am currently in the process of transitioning my website to a CSS layout, and so far it's looking good. However, I am facing two specific issues with the page layout that I need help with: 1) The background image of the left-most column is not repea ...

Developing Webpart Postback logic in C# script

I am currently facing challenges with SharePoint webparts programming. I am unsure about how to trigger a postback for an object at a specific time. I have come across suggestions to use "javascript" for this purpose, but I am having trouble understanding ...

Obtain the session value in React

Currently, I am working on a React app along with a server-side application. I have successfully created a user session on the server side and now I want to retrieve its value in my React app. Can someone guide me on how to achieve this? const [user,setUse ...

Struggling to locate the 'babel-runtime/regenerator' module? Consider importing it locally versus from NPM for a seamless integration

I've been encountering issues with my babel configuration while working on an NPM module that utilizes ES6 features like async/await, static class methods, and import/export. Initially, I faced the common error ReferenceError: regeneratorRuntime is n ...

What is the best way to customize the small square area found between the vertical and horizontal scrollbars?

Please take a look at the images provided below: https://i.stack.imgur.com/QVHfh.jpghttps://i.stack.imgur.com/cubd8.jpg Whenever both vertical and horizontal scrollbars intersect, it results in a square space. This phenomenon occurs not just within the b ...

MySQL and AJAX work together seamlessly in one, yet encounter compatibility issues in the other

I am utilizing AJAX to send a "load call" to a PHP script that includes data to be inserted into a database. The script is structured in the following way: <?php $create_tables = " CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL PRIMARY KEY ...

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

Struggling with incorporating a search feature? Encounter the error message "TypeError: data.filter is not a function"?

UPDATE: here is what console.log(data) shows. The data appears correctly, but the filtering process seems to be malfunctioning.] !https://imgur.com/a/SsEDAKj! UPDATE 2: this.state.items represents an array. I am currently working on integrating a search ...

Implementing the jQuery datepicker in Angular.js can be challenging

I recently started learning Angular.js and have been working on a web application using this framework. I am now looking to include a datepicker in one of my forms. Below is the code snippet that I have implemented: app.js myapp.directive(& ...

Attempting to adjust numerical values to display with precise two decimal places using jQuery

Possible Redundancy: JavaScript: how to format a number with only two decimal places I'm getting confused while using variables and now I can't seem to get the calculation working correctly. Any ideas? $("#discount").change(function(){ ...