document.getElementbyId() returning null [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
In the code at the line marked as //Error in comments. I get Javascript error saying: "Cannot read property style of 'null'". I have no idea what it is not able to find the object. I have thought and tried everything. Please help. Here is the code:
<script type="text/javascript">
$.getJSON('https://graph.facebook.com/647045111?fields=first_name&<%= Session["Token"] %>',
function (data) {
$('#userName').html(data.first_name);
});
document.getElementById('connectedUnregistered').style.display = 'block'; //Error
</script>
<div id="userName"></div>
<div id="disconnected" style="display:block;">
<div id="heading">Facebook login</div>
<div id="fbConnectButton"><img src="/Content/Images/fbconnect.png"/></div>
</div>
<div id="connectedUnregistered" style="display:none">
<div id="heading">Register Now</div>
</div>

You are executing your javascript code BEFORE the <div id="connectedUnregistered" /> was actually created.
Also note that you did not close your <div> with a corresponding </div>.
So move your javascript code to a part below your HTML. Or execute it after the page finished loading. If you are using JQuery you can do:
<script>
$(document).ready(function() {
... your code ...
});
</script>

Put your script at the end of the HTML document instead of the beginning, and see if that solves things.
JavaScript can't edit the DOM element because it hasn't been created yet.

Perhaps try placing this code in a
$(document).ready(function(){
//Code
});
block

in my case it was because of having this line at the beginning of the jsp/html(whatever) file:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
removing it solved the problem for me(I do not remember what it was doing on my page at first place)

Also, if in some part of the code you are using document.write it's very common to get null.

The script is trying to get the element before the element is loaded. Place the script after the element or put it in a load or ready event.

The code executes prior to the element being created. Since you are using jquery, simply wrap it in document.ready:
$(function(){
// code goes here
});
This will execute after the DOM is created.

The javascript code is running before the DOM is fully available and the call fails. Try the following instead
$(document).ready(function() {
document.getElementById('connectedUnregistered').style.display = 'block'; //Error
}

This error could also indicate that the element doesn't have an ID.
<input type="text" name="myelem" />
Make sure your element has an ID.
<input type="text" name="myelem" id="myelem" />

Related

Why does JQuery .val() method sometimes return undefined when code is valid? [duplicate]

This question already has answers here:
val() vs. text() for textarea
(2 answers)
Closed 4 years ago.
Not a duplicate question; so please consider the content closely before presumption.
I've been using JQuery for years and have never seen this type of behavior before. Consider the following:
<html>
<div class="order-form-group">
<label class="order-form-label" for="guestSpecialInstructions">Special Instructions:</label>
<textarea class="order-form-textarea" id="guestSpecialInstructions" type="text"></textarea>
</div>
<div class="order-form-group">
<label class="order-form-label" for="guestReason">Reason:</label>
<textarea class="order-form-textarea" id="guestReason" type="text"></textarea>
</div>
<div class="button-container">
<input class="order-form-submit" type="submit" value="Submit">
</div>
</html>
I've observed that the following script in some instances will return 'undefined' even when "all" the more obvious reasons have been eliminated. Such as
having the incorrect selector, having more than 1 id on the page and etc.
<script>
var specInstr = $("#guestSpecialInstructions").val();
var guestReason = $("#guestReason").val();
</script>
I spent literally hours attempting to determine what the disconnect was; stripping my code to the simplest basic level and couldn't find any reasonable explanation for the behavior.
The code is contained within a simple HTML page; nothing fancy and references the JQuery repository https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
I have another project which runs in an aspx page, still the markup is identical and the .val() method works without issue.
After hours of hitting a wall I ran across the post at JQuery: .val() is not working for textarea and someone else attesting to the exact same issue using valid code and the suggestion was:
<script>
var specInstr = $("#guestSpecialInstructions")[0].value;
var guestReason = $("#guestReason")[0].value;
</script>
Then the issue is automagically resolved. Only problem I have with this is that there no one seems to have answered the question of why the JQuery .text() method sometimes return undefined when all aspects of the code is valid.
Resolutions are great but without understanding why the issue exists, really gains nothing intellectually.
If I need to change the wording of the title, let me know.
You can only use text() on a <textarea> if it is pre-populated and to return the original content
Any changes to the content by user or setting new value programatically will not alter what is returned by text() as it will always be the original pre-pre-populated content
Always use val() to get and set
var $txt = $('textarea')
console.log('text() Original content:', $txt.text())
console.log('val() Original content:', $txt.val())
$txt.val( 'Some new content')
console.log('text() after value change:', $txt.text())
console.log('val() after value change:', $txt.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="one" type="text">
Original text
</textarea>

Cannot read property 'addEventListener' of null - JavaScript

I have never used JavaScript or CSS before. I have used Actionscript and I find it similar to JavaScript.
I am making a small html page where there is a fadeInUp animation from animation.css
I wanted to do the animation myself, instead of animation.css doing it for me, for practice.
I did everything right, except the animation does not stay at the end opacity, it resets to the css-coded opacity.
I decided to do some javascripting and made this code
(the div that the two animated elements are in is called "toppart")
var beginpart = document.getElementById("toppart");
beginpart.addEventListener("animationend", giveopac, false);
function giveopac()
{
this.style.opacity=1
}
I do not know what is wrong with it (probably something wrong with syntax), but I get this console error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
(anonymous function)
Is the problem with the function or is it with variable? If something is wrong with the event listener, there are about 10 websites that are wrong.
If anybody knows what I am doing wrong, and why it is giving me the error, I would love to know.
If it is still not working it is because in the giveopac event you are trying to access this and adding style to it which is not right.Here this is window object
You might consider changing this
check the following code snippet
var beginpart = document.getElementById("toppart");
// alert(beginpart);
beginpart.addEventListener("animationend", giveopac, false);
function giveopac(event)
{
event.target.style.opacity=1;
event.target.style.background="red";
}
<body>
<div id="toppart">
<p id="first" class="moveupfade">Zane Clark</p>
<p id="subfirst" class="moveupfade">"Keter"</p>
</div>
</body>
Hope this helps;
Found the answer!
I put it after the whole body and changed it to this:
<script>
document.getElementById("toppart").addEventListener("animationend", giveopac);
function giveopac(event)
{
event.target.style.opacity=1;
}
</script>
Thanks to geeky
Make sure that you have your script tags before closing tag of body in html page.
<html>
<body>
<div id="toppart"> <p id="first" class="moveupfade">Zane Clark</p> <p id="subfirst"
class="moveupfade">"Keter"</p> </div>
<script src="myScript.js"></script>
</body>
</html>

Dynamically generated script not working

I have a contenteditable div where you type javascript which gets outputted into an empty script tag.
<div contenteditable="true" id="script-generator"></div>
<div id="save-script">Save</div>
<script type="text/shorthand" id="script">
</script>
So you write your script in the div, click save and I have some JS which gets the html of the contenteditable div and adds it to an empty script tag.
$('#save-script').click(function() {
var script = $('#script-generator').html();
$('#script').html(script);
});
So far this works. But the generated script has no effect. The browser must not recognise the script because it wasn't there on page load? How do I make the script take effect without reloading the page?
Note: The type/shortand on the script is because I'm using a plugin which converts shortand words into actual Javascript. So the user would just need to write shorthand into the contenteditable div, and the plugin would convert that to JS. This might be adding to the problem?
I don't think it works to modify an existing <script> element. If you want the script to be executed you need to add a new element.
$('#save-script').click(function() {
var script = $('#script-generator').html();
$("#script").text(script);
ShortHand.parseScripts();
});
Correct - you need to create the script tag to have it execute after load.
$('head').append($('<script />', {html: script}));
...which means you can remove your empty script tag.
I have set up a test that's similar to what you have been looking for. Take a look and see if that helps.
Working Demo
Test code:
<div id="script" style="display:none">
alert(4+4);
</div>
<input id="sLoad" type="button" value="Load/Execute Script" />
$('#sLoad').click(function(){
//You may want to append to the head
$('<script/>').append( $('#script').html() ).appendTo('#script');
});

Newbie to jQuery and get function

I am completely new to jQuery. I can't find any good documentation on the get function and was wondering if I could get some help.
I have an HTML page called me.html with just a single div called me. I want to use the following page to get the contents within the div. Even a google in the right direction would help. Thanks so much
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="data.js"></script>
</head>
<body>
<form id="form" runat="server">
<div>
<div id="me">
</div>
</div>
</form>
</body>
</html>
you don't need to use get(). This simple script should do it
<script>
var contentsOfMe = $('#me').html();
</script>
get is used for loading data from an url. You seem to be wanting to get the contents of a div
as in $("#me").text()
What about using the great documentation provided at http://api.jquery.com/jQuery.get/
EDIT. If you want to just get the text, use var myText=$('#me').html();, and if the html, use var myHtml=$('#me').html();
You will find the documentation for the function get here : http://api.jquery.com/jQuery.get/
But get is to perform an ajax request get on your server so I don't think that's what you need.
In jquery, most of the time you will "select" an element using jquery selector : $("#id")
This will select $(), this will say you are selecting an element using his id $("#name_of_the_id").
Then, you will have an object which will represent the selected element.
If you want to get all the html inside this element do :
function getHtmlFromElementId(id)
{
var element = $("#" + id);
var html = element.html();
return html;
}
Printing the return of this function will print all html code inside the element selected.
If you are seaching for a good tutorial on jquery, the w3schools' one is really good:
http://www.w3schools.com/jquery/jquery_examples.asp

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/

Categories