Suppose I have the following HTML snippet:
<input type="text" id="myinput" />
Now I want to get that DOM element using JavaScript:
var element = document.getElementById("myinput");
Works fine, no problem so far.
But when I print it inside an alert box using alert(element);, it displays object HTMLInputElement.
Is there a way to get that element name (HTMLInputElement) as a string?
(Notice that when saying "element name" I do not mean the name attribute of an element, but the name how it is displayed when using alert() for example, as described above.
In some browsers, such as Firefox (and Chrome, potentially others) you can do:
element.constructor.name; // => "HTMLInputElement"
But in general it's a bit more complicated, perhaps not even totally reliable. The easiest way might be as such:
function getClassName(o) {
// TODO: a better regex for all browsers...
var m = (o).toString().match(/\[object (.*?)\]/);
return (m) ? m[1] : typeof o;
}
getClassName(element); // => "HTMLInputElement"
getClassName(123); // => "number"
[Edit]
Or, using the "nodeName" attribute, you could write a utility function which should be generally much more reliable:
function getHtmlElementClassName(htmlElement) {
var n = htmlElement.nodeName;
if (n.matches(/^H(\d)$/)) {
return "HTMLHeadingElement";
} else if (/* other exceptional cases? */) {
// ...
} else {
return "HTML" + n.charAt(0) + n.substr(1).toLowerCase() + "Element";
}
}
(Thanks #Esailija for the smarter implementation, #Alohci for pointing out exceptional cases.)
alert(element.nodeName);
https://developer.mozilla.org/En/DOM/Node.nodeName
When passing an object to the alert() function, it implicitly calls .toString() on that object in order to get the text for the alert. You could do something like:
var element = document.getElementById("myInput");
var string = element.toString(); // this will return 'object HTMLInputElement'
then work with the string variable to get only the HTMLInputElement part.
if I've got the question correctly you should try document.getElementById("myinput").toString().
document.getElementById returns the HTML element as an object. Simply get the attribute of the object you want to display in the alert instead (e.g., alert(element.getAttribute('ID'));). Alternatively, if you want '[object HTMLInputElement]' displayed in the alert, simply call the toString() method on the object in the alert (e.g., alert(element.toString());).
Hope this helps,
Pete
Related
I have an array.
var ABCD=[{Key:"Milk",Value:"1" },{Key:"Bread",Value:"2" }];
now need to find using the key in this array (ABCD) using a dynamic string value (returned from a function myFunction("guest_user")). I am using something like this which is working in all the browsers apart from IE because of the eval() and would be great if someone can advise on this.
var entry = eval(myFunction("guest_user")).find(function(e) { return e.Key === "Milk"; });
the return value myFunction("guest_user") is ABCD which is the array name defined above.
myFunction is returning a request parameter .. .
function myFunction(key) {
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
}
The issue in IE11 is not the eval() function. It's the find() method.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find, and you'll see that find() is not supported in Internet Explorer.
You can, however, add the functionality to IE by using the Polyfill from the same link.
That said, it's best to avoid using eval() altogether. You can do so by placing your arrays in an object, such as:
var obj = {ABCD: [{Key ...}];
You can then reference the appropriate array by calling:
obj[myFunction("guest_user")].find(...
adding polyfill method (Adding a function to Array.prototype in IE results in it being pushed in to every array as an element ) and as Rick advised obj[myFunction("guest_user")].find( is working on IE.
what I have is 3 text boxes. The first one a user enters a string. The second box they enter part of the first string they want to replace. The third text box is the string that is to do the replacing.
I'm trying to use the replace() method but I dont think Im using it right or i should be using something else.
html:
<form>
Enter a string:<input type="text" id="user_string"><br>
Enter portion of previous string to be replaced: <input type="text" id="replace_string"><br>
Enter new string: <input type="text" id="add_string"><br>
<input type="button" value="Execute" onclick="BaitAndSwitch()"><br>
Result: <input type="text" id="req_4_results"><br>
</form>
Javascript:
function BaitAndSwitch(){
// create variables for the user entered data
var UserString = document.getElementById("user_string").value;
var ReplaceString = document.getElementById("replace_string").value;
var AddString = document.getElementById("add_string").value;
var Results = UserString.replace(ReplaceString, Addstring);
if (UserString.indexOf(ReplaceString) > -1) {
Document.getElementById("req_4_results").value = Results;
}
else{
alert("Something went wrong! Please check the data you entered.")
}
}
I know I'm doing something wrong. Maybe the use of variables in the .replace() method? Or maybe the if... using indexOf line?
I was essentially trying to set it up where it would check UserString with the value of ReplaceString and if it matched, it would then execute the replace() method and show results to the given HTML element. Else if the ReplaceString didn't match any thing from UserString, it would alert the user something was wrong and to check it.
JavaScript is cAsE SeNsItIvE. Please note that Document is not the same as the document object. Please use the below line:
document.getElementById("req_4_results").value = Results;
Oh and yes, as pointed out by blex, you have another typo too:
var Results = UserString.replace(ReplaceString, Addstring);
//-------------------------------------------------^ should be S
More Info: In the console, if you try both, see the result you get:
typeof Document
// "function"
typeof document
// "object"
On a side note, please do not use such Naming Conventions. Looks like you are migrating from Visual Basic.
Note that the replace() method does not modify the string that you call it on.
In your line of code:
var Results = UserString.replace(ReplaceString, Addstring);
The value of UserString will not changed as a result of having called replace() on it.
In your conditional statement:
UserString.indexOf(ReplaceString) > -1
If it is true, it means that UserString still contains at least one instance of ReplaceString within it.
That makes sense, because you wouldn't have modified UserString yet. If you want to make sure that Results no longer has any occurrence of ReplaceString, then you want to throw an error only if the following condition is true:
Results.indexOf(ReplaceString) > -1
Say I have the following element:
<div class='selector' data-object='{"primary_key":123, "foreign_key":456}'></div>
If I run the following, I can see the object in the console.
console.log($('.selector').data('object'));
I can even access data like any other object.
console.log($('selector').data('object').primary_key); //returns 123
Is there a way to select this element based on data in this attribute? The following does not work.
$('.selector[data-object.foreign_key=456]');
I can loop over all instances of the selector
var foreign_key = 456;
$('.selector').each(function () {
if ($(this).data('object').foreign_key == foreign_key) {
// do something
}
});
but this seems inefficient. Is there a better way to do this? Is this loop actually slower than using a selector?
You can try the contains selector:
var key_var = 456;
$(".selector[data-object*='foreign_key:" + key_var + "']");
I think that you may gain a little speed here over the loop in your example because in your example jQuery is JSON parsing the value of the attribute. In this case it's most likely using the JS native string.indexOf(). The potential downside here would be that formatting will be very important. If you end up with an extra space character between the colon and the key value, the *= will break.
Another potential downside is that the above will also match the following:
<div class='selector' data-object="{primary_key:123, foreign_key:4562}"></div>
The key is clearly different but will still match the pattern. You can include the closing bracket } in the matching string:
$(".selector[data-object*='foreign_key:" + key_var + "}']");
But then again, formatting becomes a key issue. A hybrid approach could be taken:
var results = $(".selector[data-object*='" + foreign_key + "']").filter(function () {
return ($(this).data('object').foreign_key == foreign_key)
});
This will narrow the result to only elements that have the number sequence then make sure it is the exact value with the filter.
With a "contains" attribute selector.
$('selector[data-object*="foreign_key:456"]')
Let's say I'm generating markup through server-side code. I'm generating a bunch of HTML tags but I want to add custom client-side behavior.
With JavaScript (if I had a reference to the DOM node) I could have written:
var myDOMNode = ...
myDOMNode.myCustomAttribute = "Hi!";
Now the issue here is that I don't want to qualify every element with an unique id just to initialize data. And it's really strange to me, that there's not an easier and unobtrusive way to attach client-side behavior.
If I'm remembing this correctly, this is valid IE stuff.
<div onload="this.myCustomAttribute='Hi!'"></div>
If I was able to do this, I should be able to access it's "data context" though the identifier 'myCustomAttribute', which is really what I want.
The following will work but not validate:
<div myattribute="myvalue"></div>
But if you are injecting it into the HTML with Javascript, then perhaps that's not concern for you. Otherwise, you can use something like jQuery to process the elements before adding them to the DOM:
$(elements).each(function(){
$(this).attr('myattribute','myvalue');
});
First off you should access custom attributes using the getAttribute and setAttribute methods if you want your code to work on other browsers than IE.
As to your event handler question that really depends on how you add the event handler.
Assigning a function directly to the elements onXXXX property would allow you access the the element via this.
If you use IE's attachEvent you can't use this, you can access the element that generated the event using event.srcElementbut that may be child element of the div. Hence you will need to test for the existance of myCustomAttribute and search up the ancestors until you find it.
I do appricate the input but I've finally figured this out and it's the way I go about initialization that has been the thorn in my side.
What you never wan't do is to pollute your global namespace with a bunch of short lived identifiers. Any time you put id="" on an element you're doing exactly that (same thing for any top level function). By relying on jQuery, HTML5 data and CSS there's a solution to my problem which I think is quite elegant.
What I do is that I reserve a CSS class for a specific behavior and then use HTML5 data to parameterize the behavior. When the document is ready, I query the document (using Query) for the CSS class that represents the behavior and initialize the client-side behavior.
I've been doing a lot of ASP.NET and within this context both the id="" and name="" belongs to ASP.NET and is pretty useless for anything else than internal ASP.NET stuff. What you typically find yourself doing is to get at a server-side property called ClientID you can refer to this from client-side JavaScript, it's a lot of hassle. They made it easier in 4.0 but fundamentally I think it's pretty much broken.
Using this hybrid of CSS, HTML5 data and jQuery solves this problem altogether. Here's an example of an attached behavior that uses regular expressions to validate the input of a textbox.
<input type="text" class="-input-regex" data-regex="^[a-z]+$" />
And here's the script:
$(function () {
function checkRegex(inp) {
if (inp.data("regex").test(inp.val()))
inp.data("good-value", inp.val());
else
inp.val(inp.data("good-value"));
}
$(".-input-regex")
.each(function () {
// starting with jQuery 1.5
// you can get at HTML5 data like this
var inp = $(this);
var pattern = inp.data("regex");
inp.data("regex", new RegExp(pattern));
checkRegex(inp);
})
.keyup(function (e) {
checkRegex($(this));
})
.change(function (e) {
checkRegex($(this));
})
.bind("paste", undefined, function (e) {
checkRegex($(this));
})
;
});
Totally clean, no funky id="" or obtrusive dependency.
In HTML5 there are HTML5 data attributes introduced exactly for the case.
<!DOCTYPE html>
<div data-my-custom-attribute='Hi!'></div>
is now corect, validating html. You can use any name starting with data- in any quantity.
There is jQuery .data method for interaction with them. Use .data( key ) to get, .data(key, value) to set data-key attribute. For example,
$('div').each(function () {
$(this).html($(this).data('myCustomAttribute')).data('processed', 'OK');
});
How about this?
<script>
function LoadElement(myDiv)
{
alert(this.myCustomAttribute);
}
</script>
<div onload="LoadElement(this)"></div>
not tested btw
Since you're trying to do this for multiple elements, you may try name attributes and getElementsByName.
<div name="handleonload">...</div>
window.onload = function () {
var divs = document.getElementsByName('handleonload');
for (var i = 0; i < divs.length; i += 1) {
divs[i].foo = 'bar';
}
};
Alternatively, you can use selectors, using libraries (such as jQuery and Prototype) and their respective iterators. This will also allow for you to search by other attributes (such as class).
Though, be cautious with your terminology:
obj.property = value;
<tag attribute="value">
<div style="width:100px;height:100px;border:solid black 1px" myCustomAttribute='Hi!' onclick="alert(myCustomAttribute);"></div>
The onload event is used for server side events. Its not part of the standard html element events.
Take a look at the following functions (especially the walk_the_dom one):
// walk_the_DOM visits every node of the tree in HTML source order, starting
// from some given node. It invokes a function,
// passing it each node in turn. walk_the_DOM calls
// itself to process each of the child nodes.
var walk_the_DOM = function walk(node, func) {
func(node);
node = node.firstChild;
while (node) {
walk(node, func);
node = node.nextSibling;
}
};
// getElementsByAttribute takes an attribute name string and an optional
// matching value. It calls walk_the_DOM, passing it a
// function that looks for an attribute name in the
// node. The matching nodes are accumulated in a
// results array.
var getElementsByAttribute = function (att, value) {
var results = [];
walk_the_DOM(document.body, function (node) {
var actual = node.nodeType === 1 && node.getAttribute(att);
if (typeof actual === 'string' &&
(actual === value || typeof value !== 'string')) {
results.push(node);
}
});
return results;
};
With the above two functions at hand, now we can do something like this:
some link
<script>
var els = getElementsByAttribute('dreas');
if (els.length > 0) {
els[0].innerHTML = 'changed text';
}
</script>
Notice how now I am making finding that particular element (which has an attribute called dreas) without using an id or a class name...or even a tag name
Looks like jQuery is the best bet for this one based on my searching. You can bind an object to a DOM node by:
var domNode = ...
var myObject = { ... }
$(domNode).data('mydata', mymyObj);
then you can call the data back up the same way, using your key.
var myObect = $(domNode).data('mydata');
I assume you could also store a reference to this within this object, but that may be more info then you really want. Hope I could help.
HI All,
I have a piece of javaScript that removes commas from a provided string (in my case currency values)
It is:
function replaceCommaInCurrency(myField, val)
{
var re = /,/g;
document.net1003Form.myField.value=val.replace(re, '');
}
'MyField' was my attempt to dynamically have this work on any field that I pass in, but it doesn't work, I get errors saying 'MyField' is not valid. I sort of get my, but I thought this was valid.
I am calling by using: onBlur="replaceCommaInCurrency(this.name, this.value);return false;"
this.name and this.value are passing in the right values...field name and its value.
How do I do this dynamically?
-Jason
You can use eval to make your code snippet work:
eval("document.net1003Form." + myField + ".value=val.replace(re, '');");
As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those:
document.net1003Form[myField].value=val.replace(re, '');
Alternatively, try something like this:
function replaceCommaInCurrency(field){
var re = /,/g;
field.value = field.value.replace(re, '');
}
Which gets called like so:
onBlur="replaceCommaInCurrency(this); return false";
You should consider using a javascript toolkit for things like this. You could set a class like "currency" on each input, then use this snippet of jQuery based Javascript to handle everything:
$(function(){
$("input.currency").bind('blur', function(){
this.value = $(this).val().replace(',', '');
})
});
This code would fire on document ready, attach an event handler to each input with currency as its class, and then do the replacements. Note that you don't need a regex for replacement as well.
If you code it right into the markup like that, e.g. onblur="replaceCommaInCurrency(this)", the control originating the event gets passed as the parameter. Then you should be able to do something like:
myField.value = myField.value.replace(re, '');
with jQuery:
var jqField = $(myField);
jqField.val(jqField.val().replace(re, ''));
In general, you should be using a framework that will handle low level functionality like this, but the specific answer to your question is to use bracket notation for the field name:
function replaceCommaInCurrency( myField, val)
{
var re = /,/g;
document.net1003Form[myField].value=val.replace(re, '');
}
function removeCommaInCurrency(myField)
{
var re = /,/g;
myField.value=myField.value.replace(re, '');
}
-- and then call it like this:
<input type="text" name="..." onchange="removeCommaInCurrency(this);">
flatline and roenving's solution with ‘this’ is the cleaner approach, it also avoids the problems of ‘document.formname.fieldname’.
(Use ‘document.forms.formname’ to access a form without possible clashing on forms having the same name as members of the document object, and ‘forms.elements.fieldname’ to do the same with fields. Like all JavaScript object, object[namevariable] can also be used. Or, better, add IDs and use the unambiguous document.getElementById method.)
By moving binding into the script you can also remove the inline JavaScript of the onclick attribute, making the markup cleaner still:
<input type="text" class="number" name="something" />
...
<script type="text/javascript"> // external script is best, linked after all forms
function numberfield_bind() {
var inputs= document.getElementsByTagName('input');
for (var inputi= inputs.length; inputi-->0;)
if (inputs[inputi].className=='number')
inputs[inputi].onchange= numberfield_change;
}
function numberfield_change() {
this.value= this.value.split(',').join('');
}
numberfield_bind();
</script>