Why can only forms be referenced by dot notation? - javascript

It seems like a simple beginners question, but I'm unable to find an answer anywhere.
Let's say I have this HTML:
<form name="myForm">
<input type="text" name="myTxt">
</form>
then I can use the following javascript
document.myForm.myTxt.value = 'foo';
But what if I have a div instead of a form?
<div name="myDiv">
<span name="mySpan"></span>
</div>
Why can't I do the same thing here, like
document.myDiv.mySpan.innerHTML = "bar";
Seems like it should be possible to do, instead of having to use getELementById(), but I can't make it work.

As designed by W3C.
There's really nothing to argue about. You can access the an HTMLCollection of all the forms on the page through document.forms, much like you can images with document.images, applets with document.applets, links with document.links and anchors with document.anchors.
http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-1689064

The syntax you've posted is for form, to be specific.. It will work only with forms..
You will need to use following line to make it work for divs...
document.getElementsByName("myDiv")[0].getElementsByTagName("span")[0].innerHTML = "bar";
There are other ways to do this too...

Related

Access from input directly from id [duplicate]

This question already has answers here:
Why don't we just use element IDs as identifiers in JavaScript?
(5 answers)
Closed 8 years ago.
Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
why window[id] === document.getElementById( id )
I've just come across something in html/javascript which has surprised me a bit. When obtaining a reference to an html element, using javascript, I have always previously used either jQuery or document.getElementById. It also appears that you can directly access a element simply by using it's id. Can someone explain the nuances of this? I've googled but cannot find any reference to this ability, every site talks about getElementById.
The following page snippet illustrates this.
<html>
<head>
</head>
<body>
<input type="button" value="getElement" onclick="document.getElementById('blah').innerText = 'getElementById'" />
<input type="button" value="direct" onclick="blah.innerText = 'direct';" />
<div id="blah"></div>
</body>
Many thanks in advance.
Being able to select elements on the page based on their [id] is a "feature" from early JavaScript (DOM lvl 0 or 1 methinks, can't seem to find the source).
Unfortunately it's a temperamental feature. What would happen if you had:
<div id="window"></div>
or
<div id="document"></div>
Better yet, what happens here?
<div id="foo"></div>
<div id="bar"></div>
<script>var foo = document.getElementById('bar');</script>
So the nuances to calling an element based on it's [id] is simply this:
Don't use it.
It's not consistent, and not guaranteed to receive future support.
Personally I'd like to see this "feature" go the way of document.all. It only causes more issues than it solves, and document.getElementById, while certainly verbose, is meaningful and understandable.
Using getElementById is more flexible and readable. For instance, this won't work:
<input type="button" value="direct" onclick="document.innerText = 'direct';" />
<div id="document"></div>
for obvious reasons, but this will:
<input type="button" value="getElement" onclick="document.getElementById('document').innerText = 'getElementById'" />
<div id="document"></div>
and it's more clear to other developers what's really going on.
I don't believe it's a documented feature, and it doesn't appear to work in Firefox (6), but it appears to work in the latest version of Chrome, as well as IE 6-9.
I wouldn't rely on it, and would just consider it one of the oddities of browsers features.

parse <script> tag with js/jQuery

I have a HTML page where a user is able to edit a HTML resource (using ACE Editor). Within this HTML source, there is a <script>-tag, which does some pretty basic stuff.
Is there any elegant solution to parse the script tag in order to (e.g.) evaluate the variables used within the script tag? For "normal" tags I use parseHTML() to have the html as a jQuery object.
From this example, I would like to retrieve the value of $myVal (which is "f00") and write it to #myLabel:
<textarea id="myScript" rows="5" readonly>
<script>
$myVal = "f00";
</script>
</textarea>
<label id="myLabel">Hello</label>
$(function(){
$scriptVar = $('#myScript').text;
// parse the $scriptVar
// retrieve the value of, $myVal, write it to #myLabel
//$myParsedValue = ???
//$('#myLabel').text('bar!');
});
And here is the fiddle: https://jsfiddle.net/stepdown/jqcut0sn/
Is this possible at all? I don't really care about vanilla js, jQuery, regex or maybe even an external library for that purpose.
Thanks to #JeremyThille, who pointed me to the right direction. I found out, what I want to achieve is possible through jQuerys $.globalEval() - see the official documentation.
Basically what globalEval() does: it runs the script which is written in the <textarea> and makes the variables / functions globally accessible.
IMPORTANT: this implies, that syntax errors (etc) by the user will break the evaluation, and sequential functionality could be flawed. Also, the new variables are GLOBAL, so basically a user could rewrite scripts on the hosting page. (In my case both problems are of minor importance, since this is an internal application for trained users - they also have syntax highlighting through the amazing ACE editor. But I wanted to make sure to point it out. Also, there are several articles regarding the risks/ouch-moments when using eval()...)
I updated the fiddle to achieve what I wanted: https://jsfiddle.net/stepdown/Lxz7q6uv/
HTML:
<textarea id="myScript" rows="5" readonly>
$myVal = "f00";
</textarea>
<hr />
<label id="myLabel">Hello</label>
Script:
$(function(){
var myScriptContent = $('#myScript').text();
$.globalEval(myScriptContent);
console.log($myVal);
$('#myLabel').text($myVal);
});

Get onClick element to return to the main element?

I'm awful with javascript and I'm having a problem with this one.
I'm using this code
<script>
function changeNavigation(id){
document.getElementById('members')
.innerHTML=document.getElementById(id).innerHTML
}
</script>
and HTML
`<span onClick="changeNavigation('members')" >MEMBERS</span>
<span onClick="changeNavigation('help')" >HELP</span>`
<div id="members>...</div>
<div id="help" style="display: none;>...</div>
But I can't get <span onClick="changeNavigation('members')" >MEMBERS</span> to actually go to an element "members" without duplicating everything inside of it in another id.
Is there a way to do this?
This can be done using only standard javascript, but personally I'd recommend going ahead and getting used to using jQuery. Here's an example jsfiddle using jQuery: http://jsfiddle.net/JnvCR/2/
Don't forget to include jQuery in your website:
<script src="http://code.jquery.com/jquery.js"></script>
You need to correct your syntax errors. Use onclick instead of onClick (pedantic). Make sure you close your attributes properly, you are missing a few closing " marks.
updated html
<span onclick="changeNavigation('members')" >MEMBERS</span>
<span onclick="changeNavigation('help')" >HELP</span>`
<div id="members">...</div>
<div id="help" style="display: none;">...</div>
There is also an error with your logic as you are simply replacing the contents of div#members with itself.
Updated JS without syntax errors, but still with dodgy logic
function changeNavigation(id){
document.getElementById('members').innerHTML=document.getElementById(id).innerHTML;
}
Demo fiddle
http://jsfiddle.net/ADGCV/
As far as your actual question goes, can you explain what you would like to happen a bit better??
Here's a possible solution http://jsfiddle.net/ADGCV/1/

getElementById Not Working Right

Ok, so I'm REALLY new to programming and javascript, but I'm having a problem with this little string of code. The thing that is bothering me about it, is that I have done things similar to this in other programs, but it's just not working right in this specific little part of this program. Here is basically what isn't working:
<html>
<script type="text/javascript">
function test()
{
var myTextField = document.getElementById('myText');
document.write (myTextField);
}
</script>
<form>
<input type="text" id="myText">
<input type="submit" value="submit" OnClick="test()">
</form>
</html>
When I do this, it returns [object HTMLInputElement] instead of the value of that text field. Thanks for any help cause I'm most of you know this. :P
getElementById returns the Object itself, which has many methods and properties as members.
You need to reference the value property, like this:
document.getElementById('myText').value;
That should work :)
Also, here's a general reference: https://developer.mozilla.org/en/A_re-introduction_to_JavaScript
Try:
document.write (myTextField.value);
function test()
{
var myTextField = document.getElementById('myText').value;
alert(myTextField);
// or
console.log(myTextField);
}
You should not use document.write here, as you document is already loaded. Document.write will remove the page.

Directly reference HTML elements [duplicate]

This question already has answers here:
Why don't we just use element IDs as identifiers in JavaScript?
(5 answers)
Closed 8 years ago.
Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
why window[id] === document.getElementById( id )
I've just come across something in html/javascript which has surprised me a bit. When obtaining a reference to an html element, using javascript, I have always previously used either jQuery or document.getElementById. It also appears that you can directly access a element simply by using it's id. Can someone explain the nuances of this? I've googled but cannot find any reference to this ability, every site talks about getElementById.
The following page snippet illustrates this.
<html>
<head>
</head>
<body>
<input type="button" value="getElement" onclick="document.getElementById('blah').innerText = 'getElementById'" />
<input type="button" value="direct" onclick="blah.innerText = 'direct';" />
<div id="blah"></div>
</body>
Many thanks in advance.
Being able to select elements on the page based on their [id] is a "feature" from early JavaScript (DOM lvl 0 or 1 methinks, can't seem to find the source).
Unfortunately it's a temperamental feature. What would happen if you had:
<div id="window"></div>
or
<div id="document"></div>
Better yet, what happens here?
<div id="foo"></div>
<div id="bar"></div>
<script>var foo = document.getElementById('bar');</script>
So the nuances to calling an element based on it's [id] is simply this:
Don't use it.
It's not consistent, and not guaranteed to receive future support.
Personally I'd like to see this "feature" go the way of document.all. It only causes more issues than it solves, and document.getElementById, while certainly verbose, is meaningful and understandable.
Using getElementById is more flexible and readable. For instance, this won't work:
<input type="button" value="direct" onclick="document.innerText = 'direct';" />
<div id="document"></div>
for obvious reasons, but this will:
<input type="button" value="getElement" onclick="document.getElementById('document').innerText = 'getElementById'" />
<div id="document"></div>
and it's more clear to other developers what's really going on.
I don't believe it's a documented feature, and it doesn't appear to work in Firefox (6), but it appears to work in the latest version of Chrome, as well as IE 6-9.
I wouldn't rely on it, and would just consider it one of the oddities of browsers features.

Categories