Basic JavaScript framework centered around the Document Object Model (DOM) with a module structure similar to jQuery. Currently facing challenges with

In order to create a simple framework with jQuery style, I have written the following code:

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

function smpObj(selector) {
    this.length = 0;
    if (!selector ) {
        this.el = [];
        return this;
        }
    if(typeof selector == 'string'){
        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.length = this.el.length;
            return this;
        } else {
            this.el = document.getElementsByTagName(selector);
            this.length = this.el.length;
            return this;
        }
    }
    else return null;           
}
window.smp.changeColor=function smpColor(color) {
    for (var i = 0; i < this.length; i++) 
            this.el[i].style.color = color;
    }
})(window);

It is currently functioning properly. I can make a call like this:

smp('div')

However, when I attempted to add the following method:

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

It is not working as expected.

smp('div').changeColor('color')

(I am unable to call it in this manner)
I would appreciate any guidance on where I may be going wrong.
This code was influenced by an article that I read.

Answer №1

When you use return this in the smpObj function, it means that this refers to an instance of smpObj, not window.smp. Also, there is no changeColor method for smpObj.

To make it functional, you can follow these steps:

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

  function smpObj(selector) {
    this.length = 0;
    this.changeColor = function applyColor(color) {
      for (var i = 0; i < this.length; i++) this.el[i].style.color = color;
    };
    if (!selector) {
      this.el = [];
      return this;
    }
    if (typeof selector == "string") {
      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.length = this.el.length;
        return this;
      } else {
        this.el = document.getElementsByTagName(selector);
        this.length = this.el.length;
        return this;
      }
    } else return null;
  }
})(window);

After implementing the above changes, you can test it by running:

smp('div').changeColor('red')

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

Tips for making content vanish or remain concealed behind a see-through header during page scrolling

I made a JavaScript fiddle http://jsfiddle.net/claireC/8SUmn/ showcasing a fixed transparent header. As I scroll, the text scrolls up behind it. How can I make the text disappear or be hidden behind the transparent div when scrolling? Edit: I should also ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Guide to obtaining specific top elements from an array using JavaScript

I'm seeking assistance with sorting arrays in JavaScript. Here is an example of a sorted array: mainArray : [25 20 20 20 18 17 17 15 12 12 10 5 5 ] The mainArray may contain duplicate values. A. Dealing with duplicates Based on user input, I need ...

Troubleshooting: :before element not being hidden by jQuery slidetoggle()

My elements are all behaving correctly with the slidetoggle() function, except for my li:before class. I've attempted to manipulate the overflow, visibility, display, and other properties of both the :before pseudo-element and the li element, but the ...

Here is a guide on how to ensure that the div elements automatically fill the available space

Looking at this html page: Check out the jsFidlle Demo here I am aiming to have the boxes fill up the space effortlessly, each with equal width but varying heights. This is similar to the layout in Google Keep notes ...

Having trouble with validation not functioning correctly when adding a new row?

I have a table that includes a 'delete link' in each row, and at the bottom of the table, there is an add additional file link. When you click on the add additional link, it will add a new row (a label called "file", a browse button, and a text ...

ngRepeat does not iterate through an array

Presented below is an object: { "_id" : ObjectId("5454e173cf8472d44e7df161"), "questionType" : 0, "question" : "question1", "answers" : [ { "content" : "answer1" }, { "is_true" : "true", ...

Pausing JavaScript Execution Until the Completion of an Ajax Call

As I edit values in a form fetched from the database via AJAX, clicking an element opens a modal box. The details are then fetched from the server and placed in the appropriate form elements. The data contains a pin code, and I need to retrieve all the ar ...

Error! React is unable to find the window object

I recently added the "react-speech" package to my application in order to incorporate text-to-speech functionality. However, upon importing the package, I encountered an error that has been challenging to resolve despite extensive research. Any assistance ...

Skip creating declarations for certain files

src/ user.ts department.ts In the scenario outlined above, where there are two files in the src directory (user.ts and department.ts), is there a way to exclude the generation of declaration files specifically for department.ts when running tsc wi ...

Utilize checkbox filters to refine search results within jQuery pagination

$(document).ready(function(){ function loading_show(){ $('#loading').html("<img src='imagesnew/searching.GIF'/>").fadeIn('fast'); } function loading_hide(){ $('#loading').fadeOut('fast&apos ...

The noclose feature in Twitter Bootstrap is malfunctioning when placed within a div

I have a PHP page named a.php that contains the following code: <ul class="dropdown-menu noclose"> This code functions correctly, preventing the drop-down menu from closing until the user clicks outside the box. However, when I load the entire a.p ...

Checking email existence through remote jQuery validation

Utilizing the jQuery validator plugin, I am implementing an ajax function with a remote method to validate whether an email already exists in my database. However, I am encountering an error when making the ajax call within my validation function. "email ...

Steps to Hide a Material-UI FilledInput

Trying to format a FilledInput Material-ui component to show currency using the following package: https://www.npmjs.com/package/react-currency-format Various attempts have been made, but none seem to be successful. A codesandbox showcasing the issue has ...

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...

Using props in the v-bind:src directive with Vue - a comprehensive guide!

I have a Vue application with a Block component that needs to display an image. The Block component is used multiple times in the App component, each time passing a value to determine which image src to choose from an array. When I try to print {{ this.Im ...

Having trouble interacting with an xpath-selected element in Selenium using Python?

I've been attempting to click on an element that I've selected using Xpath, but it appears that I am unable to locate the element. Specifically, I'm trying to click on the "Terms of Use" button on the page. The code snippet I've written ...

Tips for effectively redirecting traffic to another website

Is there a way to redirect someone from a page URL like example.com/2458/233 to example2.com/2458/233? The first URL contains only a file that redirects to the other domain. Can anybody provide instructions on how to achieve this process? To clarify furt ...

Material-UI now offers the ability to customize the shadows array within createMuiTheme to support up to 25 different elevations

Currently working on removing shadows in the Material-UI theme. Came across this useful solution that fixed the issue. However, encountered an error related to this topic. const theme = createMuiTheme({ palette: { primary: { light: red[300], ...

Having trouble retrieving the data property from the parent component within the child component slot

I am facing an issue with my Vue components. I have a rad-list component and a rad-card component. In the rad-list component, I have placed a slot element where I intend to place instances of rad-card. The rad-card component needs to receive objects from t ...