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

'Error: Object does not have access to the specified property or method 'values'

I've been working on writing some code to retrieve and read a JSON file. It seems to work fine in Chrome, but I'm running into issues with IE11, which is the browser I need to use. I've tried changing variable names, but the problem persists ...

What are some ways to utilize symbol fonts such as marvosym within a web browser?

Are you looking to use special LaTeX fonts like \Pluto from marvosym in your web development projects? Wondering how to display this symbol with HTML / JavaScript / CSS without relying on an image? You can download the font from This symbol corresp ...

Challenges with implementing CSS transitions

I've been delving into CSS3 transitions, and I'm encountering some confusion. I can't tell if I'm misunderstanding something or if it's the browsers causing issues. Initially, I believed Opera had transition support starting from ...

Injecting JSON response data into HTML using jQuery

How can JSON return data be properly appended into an img src tag? HTML <a class="bigImg rght" style="width:258px;"> <img src="" alt="Slide" width="298" height="224" /></a> Using Ajax to Update Image Source: var parent_img = $(t ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

Hyperlinks functioning properly in Mozilla Firefox, yet failing to work in Internet Explorer

I'm encountering issues with my links not functioning properly in Internet Explorer. <a style="text-decoration:none;" href="<?php echo base_url();?>index.php/person/create/<?php echo $this->uri->segment(4);?>" > When I check ...

What are the best strategies for eliminating element cloning and duplication in Vue?

As a novice programmer, I've developed a web app similar to Trello. It allows users to create boards and within those boards, lists can be created. Each list is displayed uniquely with different IDs. However, the list items are displayed with the same ...

Tips on how to perform a server-side redirection to a different page in a Nextjs application without refreshing the page while maintaining the URL

I am working on a [slug].js page where I need to fetch data from an API to display the destination page. export async function getServerSideProps({ query, res }) { const slug = query.slug; try { const destination = await RoutingAPI.matchSlu ...

Submitting form data via Ajax without refreshing the page

I am trying to submit my form using Ajax without refreshing the page. However, it seems that the $_POST values are not being picked up. I don't receive any errors, but I suspect that my form is not submitting correctly. HTML Form <form action="" ...

Guide on transferring data from an API using mapped React hooks

I am working with react hooks and attempting to pass a value to the delete function and execute the put function <Fab aria-label="delete" className={classes.fab} value={vacation.id} ...

Having trouble with initiating an ajax call within the jQuery document ready function

I am currently experiencing an issue with an ajax call when attempting to submit a form to the database. Below is the code I have used: <?php include 'dbConnect.php'; include 'session.php'; ?> <form class="form" id="f ...

Please provide the text enclosed within the h1 tags

Is there a way to extract the content between <h2> </h2> tags in PHP or jQuery from each page and use it as the title of the pages to ensure uniqueness? Example: <section class="sub_header"> <h2>Contact</h2> < ...

What could be causing the TypeError I encounter when trying to import @wordpress/element?

Encountering a similar issue as discussed in this related question. This time, I've switched to using '@wordpress/element' instead of 'react-dom/client' based on the recommendation that it also leverages React functionalities. Ho ...

Send the object containing a Dictionary<string, int> parameter to the WebMethod

I encountered an error that says: "Cannot convert object of type 'System.String' to type 'System.Collections.Generic.Dictionary2[System.String,System.Int32]'","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObje ...

Switching the menu based on screen size successfully functions for the div element, however, it does not

Currently, I am working on creating a responsive menu. The structure of my menu is set up as follows: HTML: <ul id="top-menu"> <li class="active"> <a href="#">HOME</a> </li> <li> <a href="#div2">ABOUT</ ...

Using Vuex and array.findIndex but unable to locate a matching element

I am encountering an issue with the array.findIndex method. Despite being certain that there is a match in the array I am searching through, findIndex consistently returns -1. let index = state.bag.findIndex((it) => { it.id === item.id console. ...

Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click? I am loading an external .obj file: loader.load( obj, function ( object ) { createScene( object, mod.tipo, pid, cor.replace("#","0x") ); }); and adding it to a gro ...

Text below div will be displayed

When hovering over a div, an identical one will appear next to it with more information. Unfortunately, the content appears under the div but retains the styling like border-radius and background color. This is how my HTML looks: The div that needs ...

Embed a div opening tag within a jQuery function for one element, and then add a closing div tag after another element

Struggling with examples from the jquery documentation, I find it difficult to add a div before a specific list item and then close it after another using different classes for each li element. The prependTo and append functions don't seem to work as ...

Contrasting WebSQL and SQLite in terms of their utility in mobile applications and web browsers

Could you confirm if WebSQL and SQLite are the same? Are both WebSQL and SQLite available in PhoneGap? Will the JavaScript code used for WebSQL in a web browser be the same for a mobile app, or will we need different code? What advantages does WebSQL ha ...