Is document.getElementById a method that can be chained? - javascript

If I have this module pattern:
var MODULE = (function(window){
var myPublicStuff = {};
myPublicStuff.myPublicMethod = function(e){
return e;
};
return myPublicStuff;
})(window); //edit: forgot to put I have this
This works: (edited for clarity)
v = document.getElementById('some-element'); //works as expected
MODULE.myPublicMethod(v); //works.
But this does not work,
MODULE.myPublicMethod().document.getElementById('some-element');
or
document.getElementById('some-element').MODULE.myPublicMethod().
I thought that if the preceding member in the jail returned a value, you could chain it to the next link up? That does not work here, but I do not know why.
Edit: Thanks for all the answers. All I'm trying to do is get the element and have that method print it back out via chaining. That's all. if I put in 'btnPrint' I want it to give me <button type="button" id="btnPrint" class="btn">...</button> If I do getElementById at the console, that is what I get if I use a variable for my module first (which makes sense.) I only wanted to do the same thing with a chained method.
Edit: For completeness this is What Travis put on JSFiddle (thanks):
<button type="button" id="btnPrint" class="btn">...</button>
Element.prototype.myPublicMethod = function(){
//in the prototype scheme that JavaScript uses,
//the current instance of the Element is *this*,
//so returning this will return the current Element
//that we started with.
return this;
}
console.log(document.getElementById("btnPrint").myPublicMethod());
I agree. This looks bad unless absolutely necessary.

To avoid the v variable, you need to use
MODULE.myPublicMethod(document.getElementById('some-element'));
document is a global property (of the window object), you'd need to have returned that from myPublicMethod() to chain off it. Given that it is the identity function, you can even do something like
MODULE.myPublicMethod(document).getElementById('some-element');
MODULE.myPublicMethod(window).document.getElementById('some-‌​element');

Is document.getElementById a method that can be chained?
Yes. It returns an Element (or undefined if there is no match). The Element exposes a generic set of functions, and if the element is a specific type (for example a form) then it may also have a specific set of functions exposed.
Read more on the generic Element type at https://developer.mozilla.org/en-US/docs/Web/API/Element
I want to do this:
v = document.getElementById('some-element'); //works as expected
MODULE.myPublicMethod(v);
Here, v is straightforward, right? It just gets the element with id="some-element". Okay, from there you pass it into the myPublicMethod(v). When you do that, all you are doing is calling a function that returns the same value that is passed in. And nothing else, there is no assignment or storing taking place in the code you show above.
What you could have done here, if you wanted to take advantage of the chaining setup, would be to then access the v element from the returned value like this:
v = document.getElementById('some-element');
var vId = MODULE.myPublicMethod(v).id;
console.log(vId);// this will log "some-element" to the console
But this does not work,
MODULE.myPublicMethod().document.getElementById('some-element');
So above I explained that you are "calling a function that returns the same value that is passed in", remember that myPublicMethod just has return e; in it? Well that means that you are using undefined as the result since nothing was passed in using this line of code. In other words, your code above can be examined as undefined.document.getElementById('some-element') which is hopefully clearly problematic.
if I put in 'btnPrint' I want it to give me <button type="button" id="btnPrint" class="btn">...</button>
For example, your code as written would accomplish this as such:
var MODULE = (function(window){
var myPublicStuff = {};
myPublicStuff.myPublicMethod = function(e){
return e;
};
return myPublicStuff;
})(window);
console.log(MODULE.myPublicMethod(document.getElementById('btnPrint')));
<button type="button" id="btnPrint" class="btn">...</button>

You can return the document from your function if no argument passed:
var MODULE = (function(window){
var myPublicStuff = {};
myPublicStuff.myPublicMethod = function(e){
return e || document;
};
return myPublicStuff;
})();
var text = MODULE.myPublicMethod().getElementById('element').innerHTML;
console.log(text);
JSBin

Related

String Value from jQuery becomes undefined when passed as parameter

Good Day,
I am working on a pet project using NodeJS and Electron. It is basically a simple text editor at the moment. However I am running into an issue when trying to pass the value of a text-area to a function prior to saving to file.
Specifically when I call a function in another module, the value of the contents becomes 'undefined'. I suspect I am passing it incorrectly, or that it is being over-written between when I make the call and when the call executes, since strings are supposed to be passed by reference.
The code for the Renderer(index.html) is like this :
let otherModule = require('./js/otherModule.js');
let $ = require('jquery');
$('#btn_Save').on('click',() => {
// get the fileName, if empty propmt user with save dialog,
//log it to console for debugging
var contents = $('#txt_Content').val();
console.log('with:',contents.substring(0,9),'...');
var finalContents = contents; // (create a copy?)
if(//someConditionMet//)
{
var otherVar = $('#txt_Other').val();
console.log('Use:',otherVar.substring(0,9),'...');
finalContents = otherModule.someFunc(contents, otherVar);
}
//do something with final contents.
})// end of On-click
I have used console.log() to extensively evaluate the function and can confirm that up to the call to otherModule, the contents are correct, and match those in the textArea.It is once we are in the 'otherModule' that things go awry.
The code for the otherModule is like this:
const someFunc = function(contents, otherVar)
{
console.log('DoThings with:',contents.substring(0,9),'...');
// print shows the value to be undefined...
// do more things
console.log('Did stuff with otherVar:',otherVar.substring(0,9),'...');
// prints just fine as as expected.
// do more things
return someString;
}
module.exports = {
someFunc: someFunc
}
As mentioned in the comment, the very first line of the function logs the contents of the console, which displays the substring as 'undefined'.
Thank you for your time and your consideration!
// Extra context//
I have done some searching but beyond learning that strings are passed by reference and are immutable, I have not seen an answer to a question like this. There has been some discussion of closure issues, but usually in the context of events and callbacks, which I do not believe is the context here.
// Extra Information//
I have since found a solution to get my parameters to pass correctly. I have posted the answer below. I did two things:
1. Changed the function definition from 'const' to 'let'
2. Changed the order of the params, and removed the space following the comma.
If you get the value inside the if you should be fine.
if(//someConditionMet//)
{
var contents = $('#txt_Content').val(); //New line
var otherVar = $('#txt_Other').val();
console.log('Use:',otherVar.substring(0,9),'...');
finalContents = otherModule.someFunc(contents, otherVar);
}
I have found a solution to this problem. I am not certain why it makes a difference but I changed two things in 'otherModule'.
1. I changes the function from 'const' to 'let'
2. I changed the order of the parameters, removing the space after the comma
The new function header looks like:
let someFunc = function(otherVar,contents) {...}
I also updated the call to match the new order ( given):
finalContents = otherModule.someFunc(otherVar,contents);
I hope this helps someone in the future!

document.getElementsByTagName:Cannot read property 'style' of undefined

I wanna make a varible shortcut $$() so that i can use shortcut like $() [jquery] to save code in my project(ALL MY CODE IS PURE JAVASCRIPT).
when i put the string of id or class, it works all right, but when i put the tagName, it shows Cannot read property 'style' of undefined, it seems that the code is right,help,thanks
One more, is that way to defined a shortcut variable $$() to use in pure javascript environment right way? or is there any best practice to define a global variable like this?
window.onload = function(){
function $$(ele){
var pattern1 = /#/g;
var pattern2 = /\./g;
var pattern3 = /!/g;
var matches = ele.match(/[^#\.!]/g);//array
var elementS = matches.join("");
//alert(matches+elementS);
// console.log(document.getElementsByTagName(elementS));
var spaceExist = /\s/.test(elementS)
if(pattern1.test(ele)){
return document.getElementById(elementS);
}else if(pattern2.test(ele)){
//console.log(elementS);
return document.getElementsByClassName(elementS);
}else if(pattern3.test(ele)){
alert('hi');
console.log(elementS);
return document.getElementsByTagName(elementS);
}else if(spaceExist){
return document.querySelectorAll(elementS);
}
}
$$('#hme').style.backgroundColor = 'red';
$$('.myp')[0].style.backgroundColor = 'green';
$$('!h2')[0].style.display = 'none';//this not work,shows Cannot read property 'setAttribute' of undefined
}
<h1 id="hme">hi,friend</h1>
<p class="myp">mmdfdfd</p>
<h2>hhhhhh</h2>
Have you stepped through your code? Look at pattern #2:
var pattern2 = /./g;
That pattern will match any character at all given that's what the period represents in regular expressions - ref: http://www.regular-expressions.info/dot.html.
Therefore, this conditional is satisfied and returns its result:
else if(pattern2.test(ele)){
return document.getElementsByClassName(elementS);
}
Given there appears to be no element with a class name of h2 (which is the value of elementS), the return value is undefined.
Given that undefined has no properties, interrogating for the style property will produce the error you are seeing.
My advise is use one shortcut since you already using querySelectorAll:
window.$ = document.querySelectorAll.bind(document)
or if you rather need first element
window.$ = document.querySelector.bind(document)
this way you'll be able to do everything you are doing with normal css selectors and not obfuscated !tag for just tag
If speed actually matters, you will save some ticks by just having two aliases:
window.$ = document.querySelector.bind(document)
window.$el = document.getElementById.bind(document)
and calling $el when you need it specifically, instead of trying to make method polymorph.
Mister Epic's answer spots the main issue. Your h2 call is getting caught in that if statement, and that's why your error is happening. You need to make sure it doesn't get caught there, either by creating another pattern, or specifying in your second if statement that your 'ele' doesn't contain an '!'.
After that, in your third if statement:
else if(pattern3.test(ele)){
alert(hi); <---
console.log(elementS);
return document.getElementsByTagName(elementS);
The problem with this is you're going to alert(hi), but hi isn't defined. Make sure you wrap it in quotes.
Should be looking good after that.

getting the name of a variable through an anonymous function

Is it possible to find the name of an anonymous function?
e.g. trying to find a way to alert either anonyFu or findMe in this code http://jsfiddle.net/L5F5N/1/
function namedFu(){
alert(arguments.callee);
alert(arguments.callee.name);
alert(arguments.callee.caller);
alert(arguments.caller);
alert(arguments.name);
}
var anonyFu = function() {
alert(arguments.callee);
alert(arguments.callee.name);
alert(arguments.callee.caller);
alert(arguments.caller);
alert(arguments.name);
}
var findMe= function(){
namedFu();
anonyFu();
}
findMe();
This is for some internal testing, so it doesn't need to be cross-browser. In fact, I'd be happy even if I had to install a plugin.
You can identify any property of a function from inside it, programmatically, even an unnamed anonymous function, by using arguments.callee. So you can identify the function with this simple trick:
Whenever you're making a function, assign it some property that you can use to identify it later.
For example, always make a property called id:
var fubar = function() {
this.id = "fubar";
//the stuff the function normally does, here
console.log(arguments.callee.id);
}
arguments.callee is the function, itself, so any property of that function can be accessed like id above, even one you assign yourself.
Callee is officially deprecated, but still works in almost all browsers, and there are certain circumstances in which there is still no substitute. You just can't use it in "strict mode".
You can alternatively, of course, name the anonymous function, like:
var fubar = function foobar() {
//the stuff the function normally does, here
console.log(arguments.callee.name);
}
But that's less elegant, obviously, since you can't (in this case) name it fubar in both spots; I had to make the actual name foobar.
If all of your functions have comments describing them, you can even grab that, like this:
var fubar = function() {
/*
fubar is effed up beyond all recognition
this returns some value or other that is described here
*/
//the stuff the function normally does, here
console.log(arguments.callee.toString().substr(0, 128);
}
Note that you can also use argument.callee.caller to access the function that called the current function. This lets you access the name (or properties, like id or the comment in the text) of the function from outside of it.
The reason you would do this is that you want to find out what called the function in question. This is a likely reason for you to be wanting to find this info programmatically, in the first place.
So if one of the fubar() examples above called this following function:
var kludge = function() {
console.log(arguments.callee.caller.id); // return "fubar" with the first version above
console.log(arguments.callee.caller.name); // return "foobar" in the second version above
console.log(arguments.callee.caller.toString().substr(0, 128);
/* that last one would return the first 128 characters in the third example,
which would happen to include the name in the comment.
Obviously, this is to be used only in a desperate case,
as it doesn't give you a concise value you can count on using)
*/
}
Doubt it's possible the way you've got it. For starters, if you added a line
var referenceFu = anonyFu;
which of those names would you expect to be able to log? They're both just references.
However – assuming you have the ability to change the code – this is valid javascript:
var anonyFu = function notActuallyAnonymous() {
console.log(arguments.callee.name);
}
which would log "notActuallyAnonymous". So you could just add names to all the anonymous functions you're interested in checking, without breaking your code.
Not sure that's helpful, but it's all I got.
I will add that if you know in which object that function is then you can add code - to that object or generally to objects prototype - that will get a key name basing on value.
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
And then you can use
THAT.getKeyByValue(arguments.callee.caller);
Used this approach once for debugging with performance testing involved in project where most of functions are in one object.
Didn't want to name all functions nor double names in code by any other mean, needed to calculate time of each function running - so did this plus pushing times on stack on function start and popping on end.
Why? To add very little code to each function and same for each of them to make measurements and calls list on console. It's temporary ofc.
THAT._TT = [];
THAT._TS = function () {
THAT._TT.push(performance.now());
}
THAT._TE = function () {
var tt = performance.now() - THAT._TT.pop();
var txt = THAT.getKeyByValue(arguments.callee.caller);
console.log('['+tt+'] -> '+txt);
};
THAT.some_function = function (x,y,z) {
THAT._TS();
// ... normal function job
THAT._TE();
}
THAT.some_other_function = function (a,b,c) {
THAT._TS();
// ... normal function job
THAT._TE();
}
Not very useful but maybe it will help someone with similar problem in similar circumstances.
arguments.callee it's deprecated, as MDN states:
You should avoid using arguments.callee() and just give every function
(expression) a name.
In other words:
[1,2,3].forEach(function foo() {
// you can call `foo` here for recursion
})
If what you want is to have a name for an anonymous function assigned to a variable, let's say you're debugging your code and you want to track the name of this function, then you can just name it twice, this is a common pattern:
var foo = function foo() { ... }
Except the evaling case specified in the MDN docs, I can't think of any other case where you'd want to use arguments.callee.
No. By definition, an anonymous function has no name. Yet, if you wanted to ask for function expressions: Yes, you can name them.
And no, it is not possible to get the name of a variable (which references the function) during runtime.

Set document.getElementById to variable

The following works:
$ = document.form;
x = $.name.value;
This doesn't:
$ = document.getElementById;
x = $("id").value;
Any ideas on why this doesn't work or how to make it so?
The value of this depends on how you call the function.
When you call document.getElementById then getElementById gets this === document. When you copy getElementById to a different variable and then call it as $ then this === window (because window is the default variable).
This then causes it to look for the id in the window object instead of in the document object, and that fails horribly because windows aren't documents and don't have the same methods.
You need to maintain the document in the call. You can use a wrapper functions for this e.g.
function $ (id) { return document.getElementById(id); }
… but please don't use $. It is a horrible name. It has no meaning and it will confuse people who see it and think "Ah! I know jQuery!" or "Ah! I know Prototype" or etc etc.
The context object is different. When you get a reference of a function you're changing that context object:
var john = {
name : "john",
hello : function () { return "hello, I'm " + this.name }
}
var peter = { name : "peter" };
peter.hello = john.hello;
peter.hello() // "hello, I'm peter"
If you want a reference function bound to a specific context object, you have to use bind:
peter.hello = john.hello.bind(john);
peter.hello(); // "hello, I'm john"
So in your case it will be:
var $ = document.getElementById.bind(document);
Don't know what you want to achieve, but this can be made working like this
$ = document.getElementById;
x = $.call(document, "id").value;
because getElementById works only when it is a function of document because of the scope it needs.
But I would recommend #Quentin's answer.
getElementById is a method of the HTMLDocument prototype (of which document is an instance). So, calling the function in global context you will surely get an "Wrong this Error" or something.
You may use
var $ = document.getElementById.bind(document);
but
function $(id) { return document.getElementById(id); }
is also OK and maybe better to understand.
If you are trying to achieve something like that I would suggest using jQuery. Their $ notation is much more powerful than just getting an element by id.
Also, if you are using any platform that already uses the $ as a variable (ASP .Net sometimes uses this) you may have unpredictable result.

Javascript notification when modifying array

I got something for the javascript developers amongst us.
I got the following class:
function MyClass(){
this.__defineSetter__("array", function(val){
alert("setter called");
this._array = val;
});
this.__defineGetter__("array", function(){
alert("getter called");
return this._array;
});
this._array = new Array();
};
Now, what happens is that when I execute
var a = new MyClass();
a.array[0] = "MyString";
alert(a.array[0]);
the getter is called twice (which is fine), but the setter is never executed, as the actual array reference does not change, only the content (I guess expected behavior).
However, I'd also need to be "notified" when the array-content is modified. Thus, the call
a.array[0] = "MyString";
should also cause a setter-call (or something similar, important is to receive a notification when the array content has changed.
Anybody into this? How can this be achieved?
As we know,alert(a.array[0]); will only trigger a.array's getter/setter,and a.array[0] equal var p = a.array; p[0] which means what you want is trigger p[0]'s getter/setter,not just p's getter/setter.
So,we can change our mind to this thinking:
add getter/setter to all items of p
so,we can do it like this:
if some like p[6] = 0 is used , which will trigger p's getter/setter , judge if all item of p has getter/setter .if not add it.
if some like p = [2,3,4] is use , simply first set getter/setter to the value.
and the code is: Jsfiddle

Categories