Why is my element null? - javascript

Why when I do an alert of the value (see below) it returns null? When an element with that ID exists?
// make reference to divs
var countdown_timer = document.getElementById("countdown_timer");
var countdown_image = document.getElementById("countdown_image");
// For element manipulation
if (type == 'image') {
var element = countdown_image;
} else if (type == 'timer') {
var element = countdown_timer;
}
alert(countdown_timer);
The div is as below..
<div class="timer" id="countdown_timer"></div>

It's possible that the javascript is being executed before the elements on your page are not loaded, thus the selector isn't finding anything. Is your javascript above the <body> tag? Try putting it after </body> and see how that works for you.
Another solution is to do:
window.onload = function () {
//put all your JS here
}

onload = function() {
// put you code here
}

Your call to document.getElementById needs to be after the markup for the div.
<div class="timer" id="countdown_timer"></div>
<script type="text/javascript">
var countdown_timer = document.getElementById("countdown_timer");
...
</script>
Alternatively, you could use the window.onload event, which would be the better way to go.

Related

How can I check whether element exists based on the classname?

As I mentioned in the title of my question, my element doesn't have id attribute. So how can I check whether it exists or not?
Here is my HTML:
<div class="classname">something</div>
Note1: I can do that if there is a id attribute like this:
var el = document.getElementById("idname");
if ( el ){
console.log("exists");
} else {
console.log("not");
}
But I want to know how can I do that based on the class name .. is it possible?
Note2: I use jQuery.
Vanilla javascript (without jQuery or any other lib):
var els = document.getElementsByClassName('className')
var first = els[0]
Notice that this is an array, since there could be many elements with that class
With jQuery:
var els = $('.className')
this will result in a jQuery object instead of a DOM element, so you better use the length() method for checking existence.
check with .length ,coz className will give you array list if exist
var el = document.getElementsByClassName("classname");
if ( el.length > 0 ){
console.log("exists");
} else {
console.log("not");
}
You need to use getElementsByClassName instead of getElementById.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
If using jQuery, please use class selector.
https://api.jquery.com/class-selector/
Try this:
if($('.classname').length > 0)
{
alert('exist');
}
You could try something like this:
if ($(".classname")[0]){ // do stuff }
This will use the jquery selector to grab all items with that class name, and attempt to access the first result (in position 0). This will fail if there are no elements with this class name.
You can use this:
var el = document.getElementsByClassName("classname");
if (el) {
console.log("exists");
} else {
console.log("not");
}
try this.this will show how to get the class in automatically document.ready or , when a button clicked.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="classname">something</div>
</body>
<script type="text/javascript">
// you can check the class name in document ready or in any other event like click
//this will show all the class names of div when document ready.
$(document).ready(function(){
var the_class_name = $("div").attr('class');
alert(the_class_name); // this put to show you the classs names
if(the_class_name == "classneme")
{
//do your coding
}
else
{
//do your coding
}
});
//if you want to get the class name when a button click and check if the class is exist
$(document).ready(function(){
$("div").click(function(){
var classnames = $(this).attr('class');
alert(classnames);
if (classnames == "your_class_name")
{
// your code here
}
else
{
// your code here
}
});
});
</script>
</html>

Local Storage error

Please someone tell me what is the problem in the code which i have written.
Js
$("button").click(function() {
document.getElementById("demo").innerHTML = document.getElementById("asd").value;
});
$(function() {
var edit = document.getElementById('demo');
$(edit).blur(function() {
localStorage.setItem("data1", this.innerHTML)
});
if (localStorage.getItem("data1")) {
edit.innerHTML = localStorage.getItem("data1");
}
});
Html
<input type="text" id="asd">
<button>asdsad</button>
<p id="demo"></p>
But the same code is working perfectly in this:
Js
$(function() {
var edit = document.getElementById('demo');
$(edit).blur(function() {
localStorage.setItem("data1", document.getElementById("demo").innerHTML)
});
if (localStorage.getItem("data1")) {
edit.innerHTML = localStorage.getItem("data1");
}
});
HTML
<div contenteditable="true" id="demo">Some text here</div>
Please some one tell me what went wrong here.
When you pass the edit variable (which contains a DOM element) into jQuery as an argument, a jQuery object is returned. That changes the scope of this inside your blur event to a jQuery object. jQuery doesn't have a property of innerHTML, so it returns undefined. JavaScript DOM elements do have an innerHTML property of course, so that's why the second example works.
One way to fix your first example is to replace this:
$(edit).blur(function() {
localStorage.setItem("data1", this.innerHTML)
});
With this:
$(edit).blur(function() {
localStorage.setItem("data1", $(this).html());
});

Why is the button disapearing?

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

Get value of dom element in ready function

I want my textArea to resize when the page is fully loaded. I found that
$(document).ready(function() {
// Handler for .ready() called.
});
can help me, so I try to test it and put next code into that function:
$(document).ready(function() {
var element = $('#elementId');
alert(element.value);
});
But when the page is loading, alert shows undefined value of textArea, however there is text inside it.
How can I fetch those value inside ready function?
$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});
element isn't a DOM element but a jQuery wrapped object, it doesn't have any value property.
Use
$(document).ready(function() {
var element = $('#elementId');
alert(element.val());
});
or
$(document).ready(function() {
var element = document.getElementById('elementId');
alert(element.value);
});
or
$(document).ready(function() {
var element = $('#elementId');
alert(element.get(0).value);
});
You need to use DOM object to use value property and you have jQuery object you need to use val() on it.
$(document).ready(function() {
var element = $('#elementId');
alert(element[0].value);
//or
alert(element.val());
});

How can i dynamically Change onmouseover, onmouseout and onClick WITH parameters?

I have an image:
<img id="reqPic" src="mark.png" />
I also have declared a flag earlier on in the page:
<script type="text/javascript">
var isToolTipEnabled = true;
</script>
I now want to be able to check the flag and if its true, assign the onmouseover and onmouseout events. However, the onmousover event has to be changed to another function called Tip('string') which takes in a string. I have seen other questions on here on how to change this but it I dont see how I can pass paramters to the new function I want to change to.
The onClick would be changed to something like this:
onClick="javascript:toggleHelp('reftypeHelp');";
Any help on this would be greatly appreciated.
Thanks!
document.getElementById("reqPic").onmouseover = function() { Tip('This is the string.'); };
You could have an onload event on your body tag which calls a function that checks necessary values.
<script type="text/javascript">
var isToolTipEnabled = true;
function eventAdder() {
if (isToolTipEnabled) {
var img = document.getElementById('reqPic');
img.onmouseover = function() {
Tip('string');
}
img.onmouseout = whateverElse;
}
}
</script>
<body onload="eventAdder();">
with jQuery you could use the hover function but yeah creating an inline function works too

Categories

Resources