using abbreviated references for javascript objects

I have extremely valuable information, so I attempted to create shortcuts like the following:

Check out this LIVE example: http://jsfiddle.net/nqeUN/

var d = "document" ,
    t = "getElementByTagName" ,
    d = "div" ,
    oc = "onclick";
d[t](d)[0].oc = function(){
    alert("1");
}

Unfortunately, it's not functioning as expected. What could be the reason? I noticed that in the Google Plus API, all objects are defined as strings like this. How do they manage to make it work?

Answer №1

You must tackle a few issues that require attention

  • There are currently two values assigned to d: "document" and "div".
  • It should be getElementsByTagName
  • The getElementsByTagName function requires a DOM entry point, not a string. Change the first d to document
  • When using dot notation for .oc, it will bind to the property oc instead of the value of the variable oc. Use brackets [] notation instead

Code:

var d = document ,
    t = "getElementsByTagName" ,
    div = "div" ,
    oc = "onclick";

d[t](div)[0][oc] = function(){
    alert("1");
}

Here is a working Fiddle: http://jsfiddle.net/nqeUN/1/

Answer №2

Using strings for properties is possible, but not for variable names. Additionally, you mistakenly declare the variable d twice and use an incorrect method name. A better approach would be as follows:

var d = 'document', t = 'getElementsByTagName', div = 'div', oc = 'onclick';

window[d][t](div)[0][oc] = function() { ... }

However, this can reduce readability and complexity unnecessarily. It may be more efficient to utilize a code minimizer to automatically optimize your code while still keeping it readable during development.

Answer №3

d is actually just a string, not the document object.

To access the actual document object, you should use var d = document.


However, it's not recommended to do this manually as it can result in extremely unreadable code.

Instead, focus on writing clear and understandable Javascript code first, then utilize a minifier tool like Microsoft AjaxMin or Google Closure Compiler to automatically reduce the size of your code for production purposes.

Answer №4

After updating the values in your specific situation, you will observe:

"document".getElementsByTagName("document").onclick = function() {};

1.) Ensure that variable d is assigned the actual global document reference, not just the string 'document'

var d = window.document;

2.) The method getElementsByTagName retrieves nodes matching the specified tag name within the DOM node provided; therefore, passing 'document' as a string would search for HTML elements named 'document'. Instead, search for div elements like this:

d.getElementsByTagName("div"); // Retrieves all 'div' elements in the document

3.) When utilizing method names as strings, remember to enclose them in brackets

document[ t ]; // Avoid using document.t as it won't work since t is not a member

4.) Once you have selected the desired nodes, iterate through them to attach event handlers to each element

var d = document.getElementsByTagName("div"),
    i = 0,
    len = d.length;

for ( ; i < len; i++ ) {
    (function() {
        // Perform actions with d[i], the current element in the loop
    })(i)
}

I trust this explanation proves beneficial! Best wishes.

Answer №5

The issue arises because the variable d is set as a string, and the String object does not support the getElementByTagName method.

Additionally, there is a redeclaration of the d variable as the string div, so it should be assigned a different name:

var d = "document",
    t = "getElementByTagName",
    e = "div",
    oc = "onclick";

To resolve this, you have to access the window object first and then get the document attribute from it:

window[d]

This will allow you to retrieve the Document element and then access the getElementsByTagName method (note the plural form):

window[d][t]

Next step is to call this method, provide the element name, grab the first value from the array that is returned, and assign a function to the onclick attribute:

window[d][t](e)[0][oc] = function () {
    alert("1");
};

Answer №6

const doc = "document",
    tags = "getElementsByTagName" ,
    div = "div" ,
    click = "onclick";
window[doc][tags](div)[0][click] = function(){
    alert("1");
}
  1. ) The variable document is now declared as const
  2. ) Using call method on getElementByTagName to access 'div'
  3. ) Changed accessor from dot to bracket for oc variable since it is a string
  4. ) Removed duplicate declaration of the variable d
  5. ) Corrected spelling from getElementByTagName to getElementsByTagName

Answer №7

Experience the thrill of manipulating strings http://jsfiddle.net/nqeUN/8/

"document"["gg"]()["getElementsByTagName"]("div")["0"]["onclick"] = function(){alert(1);};

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

Utilizing Python along with Selenium WebDriver to effectively pause and activate a clickable button that is in plain sight

I am currently facing a challenging situation trying to interact with a button using Webdriver. The button remains hidden until a value is inputted into a preceding field. Despite my attempts to use sleeps and explicit waits, I have not been successful. I ...

Combining data using D3's bar grouping feature

I'm currently exploring ways to group 2 bars together with some spacing between them using D3. Is there a method to achieve this within D3? I found inspiration from this example. var data = [4, 8, 15, 16, 23, 42]; var x = d3.scale.linear() .doma ...

Check if a rotated rectangle lies within the circular boundary of the canvas

I have a rectangular shape that has been rotated using the ctx.rotate method, and there is also an arc on the canvas. My goal is to determine if any part of the rectangle lies within the boundaries of the arc. See the example below: https://i.sstatic.net/ ...

Manipulate the JQuery code to alter the window's location

I am currently implementing ajax for loading my website content and am looking for a way to update the window location upon successful ajax completion. Is it feasible to update the window location to "/newpage" in order to allow users to navigate back and ...

Is there a way to use jQuery to automatically make a field stand out visually?

I am looking for a way to make a text field automatically underline as the user types. The line should follow along with the characters in real-time, and when the user moves away from the field, I want the line to fill up the entire width. This signifies t ...

Include the selected class in the relative URL

I am attempting to apply a highlight class to my selected category: My code looks like this : <div id="category"> <ul> <a href="category.php?c=electronic"> <li>Electronic</li> </a> ...

Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this... <div ng-app="myApp"> <div ng-controller="inControl"> I enjoy sipping on {{beverage}}<br> <input my-dir ng-model="beverage"></input> </div> </div> a ...

Displaying JSON data on an HTML page

i am currently developing a web application and i am facing an issue with retrieving data from JSON files and displaying them in table format. The problem arises when i encounter a 404 error, as i am working locally using Node.js. Edit 1: upon checking ...

What is the best way to play a random song when the user clicks a button?

My goal is to develop a website where users can click on an image and have a random song play from a playlist. I currently have a functioning code that activates one song, but it fails when adding multiple songs to the mix. <html> <head> ...

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...

Stop images from flipping while CSS animation is in progress

I've been developing a rock paper scissors game where two images shake to mimic the hand motions of the game when a button is clicked. However, I'm facing an issue where one of the images flips horizontally during the animation and then flips bac ...

Tips for styling list tooltips with CSS and Bootstrap

I am looking to style my tooltips using CSS, specifically I want the background of the tooltips to be gray and the text to be bold. The issue is that I am unsure how to do this, especially since I have a list with multiple options, each option having its ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

"Unleashing the power of Asynchronous Ajax Operations

$("#container").on("change", "#control1", function() { if ($("#checkData").val()) { $.get("/Controller/CheckData/" + $("#control2").val(), function(data1) { if(!data1.Success) { alert("Unable to do POST."); ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

Troubleshooting: Jquery form submission function not functioning as expected

My jQuery code is working fine with functions like hide(), but I am facing an issue with submit() function. When I try to submit the form, nothing happens! I would really appreciate it if someone could help me with this. Here is my form: <form class ...

What is the process for building a series of HTML elements using jQuery?

Is it possible to create a moving conveyor belt of html elements (such as divs) using jQuery, and if so, how can this be done? For example: (as shown above, rectangles move from left to right; new ones are added and the last one is removed) And then: [ ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

Build an interactive phone directory with the power of JavaScript!

Does anyone know the best way to implement this code snippet for user input and output tables using JavaScript? Take a look here This is what I have tried so far: /*index.html*/ <!doctype html> <html lang="en"> <head> <!-- Requir ...

Cordova experiencing difficulty loading platform API

Lately, I've been facing a persistent issue with Cordova. Whenever I try to run it in the browser, an error pops up saying that the browser is not added as a platform. Even when I attempt to add the browser as a platform, another error occurs stating ...