The concept of accessing a reference in JavaScript

Take a look at this code snippet:

http://jsfiddle.net/GKBfL/

I have a function called collection.prototype.add and I want it to return a reference so that the final alert will show testing, testing, 123, testing. Any ideas on how to achieve this?

Here is the HTML markup:

<span id="spantest">testing, testing, 123, testing</span>​

And here is the JavaScript code:

var collection = function () {
   this.items = {};   
}

collection.prototype.add = function(sElmtId) {
    this.items[sElmtId] = {};
   return this.items[sElmtId];
}

collection.prototype.bind = function() { 
    for (var sElmtId in this.items) {
        this.items[sElmtId] = document.getElementById(sElmtId);
    }
}
var col = new collection();
var obj = {};
obj = col.add('spantest');
col.bind();
alert(obj.innerHTML);​

Answer №1

The issue lies with this particular line of code:

this.items[sElmtId] = document.getElementById(sElmtId);

What this does is it replaces the current object assigned to this.items[sElmtId] with the actual DOM node. A better approach would be to assign the node to a property of that object instead:

this.items[sElmtId].node = document.getElementById(sElmtId);

This way, you can always access the current node using obj.node:

alert(obj.node.innerHTML);

Check out the DEMO here


On a related note: The issue with your jsfiddle is also due to executing the code before the DOM is fully constructed (no wrap (head)), resulting in the inability to locate #spantest. Make sure to run the code only after the DOM is ready, using either no wrap (body), onDomRead, or onLoad.

Answer №2

In JavaScript, creating a reference exactly as needed is not possible. One workaround is to use either a nested or closed object, or simply by copying it over as shown below:

var collection = function() {
    this.items = {};
};

collection.prototype.add = function(sElmtId) {
    return this.items[sElmtId] = {};
};

collection.prototype.bind = function() {
    for(var sElmtId in this.items) {
        var element = document.getElementById(sElmtId);

        for(var x in element) {
            this.items[sElmtId][x] = element[x];
        }
    }
};

var col = new collection();

var obj = {};

obj = col.add('spantest');
col.bind();

alert(obj.innerHTML);

However, this method won't create a true "bound" reference. For that functionality, using nested objects might be necessary, even though it may compromise the simplicity of your code.

http://jsfiddle.net/GKBfL/7/

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

angularjs issue with $setPrestine function not providing reliable results

I have encountered an issue with the login form code. Initially, I am able to reset the form fields and error messages successfully on the first attempt (both success and failure scenarios work). However, on the second try, I am unable to reset the form fi ...

Display a badge in the navbar on specific VueJS pages

I have embarked on the journey of creating a single page application using Vue 3, and I've encountered an interesting scenario where I want to display a badge in the navigation bar for specific pages. This is how my setup looks: // App.vue <templat ...

What's the best way to apply a class to a React element upon clicking it?

I'm currently working on a React component to create a hamburger menu, but I'm struggling to add a class when a button is clicked. I'm fairly new to React, so any gentle guidance would be appreciated. The code below is what I have so far, bu ...

The jstree does not seem to be generating the tree structure as expected based on

I am utilizing the jstree plugin to construct a hierarchical tree view of locations, rooms, and assets for a company within a PHP application that I am developing. The main intention behind this tree is to enable users to select an asset while going throu ...

The webpage hosted on Heroku displays a blank background, requiring users to refresh the page with an F5 key

I developed a group chat program using Python microframework flask, vanilla JavaScript, and Flask-SocketIO. The program is deployed on heroku and can be accessed here: . After deployment, I encountered the following issue: While the program worked fine o ...

Issue with onDblClick event in Angular5 and PrimeNG's p-listbox

I encountered an issue while using p-listbox's onDblClick event as it does not return the selected list element. Instead, the event object only contains the value of 'this'. {"originalEvent":{"isTrusted":true}} HTML Blockquote <!-- S ...

Send Summernote code data using Ajax to PHP which will then store it in the database

I have implemented a Summernote editor on a page where users can input content. When a user submits the page, I use jQuery to retrieve the HTML code from the editor and then send it to a PHP script for insertion into a database. The HTML retrieved before s ...

Is it recommended to exclude the NGXS NgxsLoggerPluginModule for production deployments?

When developing, it's common to use the following imports: import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; Is it recommended to remove these imp ...

Exploring the capabilities of Angular through filter functions and ng-bind-html

I created an angular filter called 'strLimit' to restrict the number of characters in a string: mod.filter('strLimit', ['$filter', function ($filter) { return function (input, limit) { if (!input) return; if (input.le ...

Combine two arrays and collapse one of the nested elements

I need help merging two arrays based on ID and flattening one of the objects. I haven't been able to find a solution for my specific case. This is what I'm attempting and what I've managed to achieve so far: const a = { someProperty: &a ...

Does the Node Schedule library create new processes by spawning or forking them?

Is the node-schedule npm module responsible for spawning/forking a new process, or do we need to handle it ourselves? var cron = require('node-schedule'); var cronExpress="0 * * * *"; cron.scheduleJob(cronExpress, () => { //logger.info(" ...

Using Three.js to add points to the scene but they are not visible

Hi there, I have a question that I need help with: I recently studied the PointsMaterial API documentation for Three.js and adapted an example to work with my existing code. The goal of my project is to render points on top of a model that is loaded when ...

Utilize the existing code to prevent multiple form submissions

My current focus is on integrating a Delete Account feature into my website. If a user requests to delete their account (please note that it takes 3 days to completely delete the data) and tries to log in within this 3-day period, we need to prompt for co ...

Create a new build for testing and debugging using create-react-app

Currently, I am in the process of developing a web application that utilizes a React frontend and is powered by a golang api layer. Although I do not have extensive experience with Javascript, I find myself struggling with the Node build system. I am loo ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

Dynamically loading pages into a div with the power of AngularJS

I am attempting to dynamically load pages into a div using a select Here is my HTML code : <div ng-app="App" ng-controller="ProjectCtrl"> <div> <select ng-model="selectedType" class="form-control" ng-change="showContent()" ng-opt ...

Issues with tangents in three.js compared to the VertexTangentsHelper with problems on display

After enabling the "vertexTangentsHelper" feature in THREE.js, I've noticed that the tangents on various geometries appear to be incorrect. I'm questioning whether these tangents are being miscalculated (possibly due to my shader output) or if t ...

Storing a JSON response in a variable

I need assistance with using the Google Geocoder API to obtain the longitude and latitude of an address for a mapping application. How can I retrieve data from a geocode request, like this example: "http://maps.googleapis.com/maps/api/geocode/json?address ...

Optimal method for storing large arrays of numbers in localStorage using JavaScript

*"Efficient" in this context refers to smaller size (to reduce IO waiting time) and fast retrieval/deserialization times. Storing times are less important in this scenario. I need to store multiple arrays of integers in the browser's localStorage, ea ...

href not functioning properly on subsequent clicks, whereas onclick remains active

I'm experiencing an issue with a button that opens a modal. When clicking the button, it's supposed to open a new page in the modal and also make an API call for processing before loading the new page. <a class="btn btn-primary" type='b ...