document.getElementById throws TypeError - javascript

I am a bit new to Javascript. I am writing this dummy script to test out what I need for my larger page. I want, at the simplest, to get the value of href and then change the value of href and then see it again. TO keep it simple, right now I have removed the part for changing the href value and just calling the attribute value twice. But the second time I access the attribute value it show an error which I have posted below. I'm posting two error logs one from Firebug and one from Dragonfly(from Opera).
Any help would be dearly appreciated. Thanks.
One more issue I have with the script is that it never finishes loading. I always see (in Firefox 3.6.8) the little loading sign going round and round in the tab title. It doesn't bother me so much but if anyone has an idea please tell me.
<!-- This file is used to set attribute value for href. -->
<html>
<head>
<script type="text/javascript">
function hrefvalue()
{
var thisthang = document.getElementById("1").childNodes[0].getAttribute("href");
document.write(thisthang);
document.write("\n");
var newnew21 = document.getElementById("1").childNodes[0].getAttribute("href");
document.write(newnew21);
}
</script>
</head>
<body>
<div id="1">click here</div>
<button type="button" onclick="hrefvalue()">Click me instead</button>
</body>
</html>
Error logs :
1. Firebug -> document.getElementById("1") is null
2. Dragonfly ->
Uncaught exception: TypeError: Cannot convert 'document.getElementById("1")' to object
Error thrown at line 8, column 0 in hrefvalue() in
file://localhost/D:/Chicago%20pics/website%20pics/website%20root/trial5.htm:
var newnew21 = document.getElementById("1").childNodes[0].getAttribute("href");
called from line 1, column 0 in (event):
hrefvalue()
And thanks again for all the fish :D

An id can't start with a number (in HTML 4). Don't bet on browsers supporting such ids.
document.write will trash a document that isn't open. When the browser parses </html> the document is closed. Since the function runs onclick, it will be closed before you try to write. Use DOM methods to modify HTML with JS.

Related

Javascript - Full string doesn't show in google chrome console, only show till first comma

//$('body').html($('img').eq(0).attr("data-images"));
console.log($('img').eq(0).attr("data-images"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-images="http://pictures.immobilienscout24.de/listings/9c34260e-96e3-4d67-9bbb-e7ccce1a6f0c-1220449977.jpg/ORIG/resize/1106x830%3E/format/jpg/quality/80,http://pictures.immobilienscout24.de/listings/7133f252-4396-40c6-9860-ccb27aee4bc7-1220449982.jpg/ORIG/resize/1106x830%3E/format/jpg/quality/80,http://pictures.immobilienscout24.de/listings/9ce7a32b-e031-4670-8689-1fe02b356d59-1220449986.jpg/ORIG/resize/1106x830%3E/format/jpg/quality/80,http://pictures.immobilienscout24.de/listings/02cf0c6c-3fb1-4c61-bd32-b74b04e95c99-1220449993.jpg/ORIG/resize/1106x830%3E/format/jpg/quality/80,http://pictures.immobilienscout24.de/listings/38878ca9-80ed-4d05-900b-82b6ac834f47-1220449995.jpg/ORIG/resize/1106x830%3E/format/jpg/quality/80,http://pictures.immobilienscout24.de/listings/e17a2405-4678-4b95-8f52-ad1d4a435368-1220449998.jpg/ORIG/resize/1106x830%3E/format/jpg/quality/80,http://pictures.immobilienscout24.de/listings/6705b14f-e757-4637-9191-7edc6df4eb79-1220450000.jpg/ORIG/resize/1106x830%3E/format/jpg/quality/80">
If you have Google Chrome browser, you will see only part of the string (till first comma), not the full string
Another question is when i add
$('body').html($('img').eq(0).attr("data-images")); before the console.log($('img').eq(0).attr("data-images")); it returns undefined, I am not sure why?
Could someone help pls?
To your first question: Chrome is simply shortening the string in the console for displaying purposes. You are still logging the complete string.
To your second question: When you do
$('body').html($('img').eq(0).attr("data-images"));
console.log($('img').eq(0).attr("data-images"));
the first line removes all inner html of the <body> tag, and writes the raw data-images string to it. In the second line, you try to select all img tags (which have been removed by the $('body').html()). This results in undefined
with:
$('body').html($('img').eq(0).attr("data-images"));
you are changing the html content of the body element. So if you execute that before your console.log statement there will be no element any more. You will see the details if you execute the statement and then inspect the html page.

Dynamically change page title from h1 tag using Javascript

First off, thanks for taking the time to read this question. What a great community Stack Overflow has :)
I need to change the title tag of a page based on the text contained in the h1 element on that page.
I've been searching around, and I have found the "document.title" Javascript function. I've been playing around with it, trying to pull the text from my h1 element that has the class of "Category-H1".
<script type="text/javascript">
document.title = document.getElementsByClassName("Category-H1");
</script>
However, it is just setting the page title to "[object HTMLCollection]", which as I understand is a null value. Is JS the best was to do this? I know my code is jacked, any tips?
Thanks in advance! - Alex
Edit
I have been informed that line of code returns a collection object and not a string. It was pointed to a code example of:
setTimeout(function () { document.title = "iFinity User Profile - " + document.getElementById("test").outerText; }, 1000);
However, this code produces a page title of "iFinity User Profile - undefined". I have the h1 element on that page set to the id of "test".
You're almost there.
[object HTMLCollection] is not a null value--it is the string representation of a collection of html elements. You want to choose the first one and then get the inner html from it.
document.getElementsByClassName("Category-H1")[0].innerHTML
Also, make sure you do this after the document has loaded. You can either do this by adding the script at the end of your document, or have it run on the onload event of the body.
This should work:
document.title = document.getElementsByClassName("Category-H1")[0].innerHTML;
The getElementsByClassName() function returns a collections of elements ( [object HTMLCollection], so you need to get an element out of it, I'm assuming the first one.
A better solution may be the following:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1")[0].innerHTML
</script>
This would save from setting a h1 class.
This is very close, but I found that - working with Firefox anyway, when you use the getElementsByTagName("H1") it gives you an array as you have recognized. However, it works better using:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1").item(0).innerHTML;
</script>
Note the addition of the .item(0).innerHTML after getting the element rather than the [0].innerHTML.
I don’t know if you have any experience in it or not, but another alternative that seems to be very popular these days is the use of jQuery. As in the earlier discussions, the code below assumes that you are interested in grabbing the first instance of the “H1” tag or the “Category-H1” class. This is an important point because unless you target an “ID” attribute, you will get a collection of items.
This code also assumes that you have already implemented the inclusion of the jQuery library either directly from your website or by referencing a CDN.
<script type="text/javascript">
$(document).ready(function () {
document.title = $("H1")[0].innerText;
});
</script>
The $(document).ready will call it’s enclosed function only after the Document Object Model (DOM) has finished loading, and before the browser’s rendering engine displays the page.
The content inside the function will grab the inner text of the first instance of the “H1” tag and assign that text value to the document’s title tag in the head section.
I hope this adds another layer of help.

Cognos Report Studio: HTML Tag issue

I'm using cognos report studio and I came to an error on my prompt page. I got my coding to work right(I tested it on a blank page), but I noticed theres a yellow explanation point on the bottom left, which doesn't allow me to continue what I'm trying to do.
Here is a screenshot:
The error seems to be coming from my html tag in the prompt page.
Here is my coding:
<script type="text/javascript">
var theSpan = document.getElementById("FiscalYear");
var theSelect = theSpan.getElementsByTagName("select");
theSelect[0].options[2].selected=true; //This will make default value in prompt to be the first item after line, change the value '2' for other item
theSelect[0].options[0].text = 'Fiscal Year';
listBoxBusinessDate.checkData();
</script>
My error should be coming from there, I just can't figure out why. Any ideas on what it could be? Thanks.
This is a JavaScript error. The variable you are trying to use "listBoxBusinessDate" is null / undefined, so when you try to call a method on it (.checkData()), you get this error.
Where is this variable defined (its not in the snippet you provided, but could be defined earlier in the file)...?

print the first link in the document

I would like to print the first link in the page with JavaScript. But when I use the following code, it doesn't work:
<html>
<head><title></title></head>
<body>
<a id="mylink" href="http://google.com">Google</a><br />
<script>
a=$('mylink').href;
document.write(document.links[0]);
</script>
</body>
</html>
Then I commented out the code "a=$('mylink').href", it suddenly worked, why? How come the varable a has any influence on the next statement?
Any answers are appreciated.
There's a few possibilities:
The object $ is not defined and caused a JavaScript error preventing your 2nd statement to execute
The $ object does not know what to do with the string passed in and errors
The returned value from $ does not have a value (ie - it returns undefined) which wont have a property href, causing a JavaScript error
the code is not working because in your example the $ object does not exist and will cause an error. It seems that you were trying to use a JavaScript framework like jQuery ($ object) but you forgot to include it.
Try to add the following script-Tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
If you wanted to use jQuery, you should also access attributes via the .attr("attrname") function. E.g.
var a = $('#mylink').attr('href');
Again if you wanted to use jQuery, you have to alter the selector from "mylink" to "#mylink" to specify that you were searching for the element with the id "mylink".
I am a bit confused as to what you are trying to do, but couldn't you just write the whole link in js? Ex:
<script>
<!--
document.write('Google');
-->
</script>
<noscript>
Google
</noscript>
The comment tag in the script is ignored and is only there so browsers that don't support javacript won't print it in the document. The <noscript> is so browsers that don't support javascript have alternate content.
It doesn't work because a=$('mylink').href fails to execute and stop executing of following code. The code document.write(document.links[0]) is correct. When you call it without previous wrong line, it just works.
I think in the first line you're trying to use jQuery library. If you want to do it, you need to include jQuery library using <script> tag, then use the following code:
document.write($('a:first').attr("href"));
Just remove the jQuery stuff, you don't need it. As you've already discovered, there is a document.links collection so if you want to print the herf value of the first link in the document:
document.write(document.links[0].href)
and you're done.

Javascript error: [elementname] has no properties

I'm doing some maintenance coding on a webapp and I am getting a javascript error of the form: "[elementname] has no properties"
Part of the code is being generated on the fly with an AJAX call that changes innerHTML for part of the page, after this is finished I need to copy a piece of data from a hidden input field to a visible input field.
So we have the destination field: <input id="dest" name="dest" value="0">
And the source field: <input id="source" name="source" value="1">
Now when the ajax runs it overwrites the innerHTML of the div that source is in, so the source field now reads: <input id="source" name="source" value="2">
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
I get the following error: Error: document.getElementById("source") has no properties
(I also tried document.formname.source and document.formname.dest and same problem)
What am I missing?
Note1: The page is fully loaded and the element exists. The ajax call only happens after a user action and replaces the html section that the element is in.
Note2: As for not using innerHTML, this is how the codebase was given to me, and in order to remove it I would need to rewrite all the ajax calls, which is not in the scope of the current maintenance cycle.
Note3: the innerHTML is updated with the new data, a whole table with data and formatting is being copied, I am trying to add a boolean to the end of this big chunk, instead of creating a whole new ajax call for one boolean. It looks like that is what I will have to do... as my hack on the end then copy method is not working.
Extra pair of eyes FTW.
Yeah I had a couple guys take a look here at work and they found my simple typing mistake... I swear I had those right to begin with, but hey we live and learn...
Thanks for the help guys.
"[elementname] has no properties" is javascript error speak for "the element you tried to reference doesn't exist or is nil"
This means you've got one or more of a few possible problems:
Your page hasn't rendered yet and you're trying to reference it before it exists
You've got a spelling error
You've named your id the same as a reserved word (submit on a submit button for instance)
What you think you're referencing you're really not (a passed variable that isn't what you think you're passing)
Make sure your code runs AFTER the page fully loads. If your code runs before the element you are looking for is rendered, this type of error will occur.
What your describing is this functionality:
<div id="test2">
<input id="source" value="0" />
</div>
<input id="dest" value="1" />
<script type="text/javascript" charset="utf-8">
//<![CDATA[
function pageLoad()
{
var container = document.getElementById('test2');
container.innerHTML = "<input id='source' value='2' />";
var source = document.getElementById('source');
var dest = document.getElementById('dest');
dest.value = source.value;
}
//]]>
</script>
This works in common browsers (I checked in IE, Firefox and Safari); are you using some other browser or are you sure that it created the elements correct on innerHTML action?
It sounds like the DOM isn't being updated with the new elements to me.
For that matter, why are you rewriting the entire div just to change the source input? Wouldn't it be just as easy to change source's value directly?
This is a stretch, but just may be the trick - I have seen this before and this hack actually worked.
So, you said:
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
Change that line to this:
setTimeout(function() {
document.getElementById("dest").value = document.getElementById("source").value;
}, 10);
You really shouldn't need this, but it is possible that the time between your setting the innerHTML and then trying to access the "source" element is so fast that the browser is unable to find it. I know, sounds completely whack, but I have seen browsers do this in certain instances for some reason that is beyond me.
Generally you shouldn't use innerHTML, but create elements using DOM-methods. I cannot say if this is your problem.

Categories

Resources