I can't figure out why document.getElementById is not working in Firefox:
document.getElementById("main").style.width = "100";
When I check in Firebug it says:
TypeError: document.getElementById("main") is null
Does anybody know why this is happening?
EDIT: Unfortunately, the "body" element was a bad example. I changed it to another element with an id of "main".
put your script before
</body>
Or, if you use your script in <head> you may change code:
$(document).ready(function() {
//enter code here.
});
Did you set the id of the <body> element to "body":
<body id="body" ...>
Update:
Check if the following example works for you: http://jsbin.com/uyeca/edit
Click the Output tab to see the result (which should be a DIV with width 600px).
https://developer.mozilla.org/En/DOM/Document.getElementById
Simply creating an element and
assigning an ID will not make the
element accessible by getElementById.
Instead one needs to insert the
element first into the document tree
with insertBefore or a similar method,
probably into a hidden div.
var element = document.createElement("div");
element.id = 'testqq';
var el = document.getElementById('testqq'); //
el will be null!
I had the same prob...I was trying to use "getElementById" without the main structure of the HTML page-- tag was missing.
After adding in my page it worked fine...I was working on a script that was supposed to be embeded on other sites--widget sort of thing.
Related
I'm using scrollIntoView function to click on a link and have it jump to a different part of my web app. The issue i am having is that i dont know how to target an HTML element called 'identifier'
so my html looks like...
<div class="subpara" identifier="2b">
<num value="b">(B)</num>
<content>some conent</content>
</div>
I want to be able to target the 'identifier' 2b in this case
i tried using:
onClickOutlineNav(id) {
let element = document.getElementById(id);
//scroll to identifier
element.scrollIntoView();
}
and it doesnt seem to be working..any ideas?
You're using incorrect html tag syntax, which would be your first problem.
<div class="subpara" id="2b">
The getElementById function looks for the "id" property on html tags, not the "identifier" property.
If you insist on using the "identifier" property, you can query for it like so:
let element = document.querySelector('[identifier="2b"]');
or more generically:
let element = document.querySelector(`[identifier="${id}"]`);
Thanks to anyone who helps me solve this issue.
So the issue is I'm trying to hide an element (by class) with an onclick event using a button. But I am unable to do so.
Here's the code on jsfiddle http://jsfiddle.net/1tpdgrnj/
Here's the code for those who wish to help me here:
HTML:
<div class="box">Hide on button click!!
<button onclick="close();">Close</button>
Javascript:
function close() {
document.getElementsByClassName("box").style.display = 'none';}
UPDATE
Refer to the answer below and to the jsfiddle to see how it's different.
See this fiddle
Change your javascript as follows
function myFunction() {
document.getElementsByClassName("box")[0].style.display = 'none';
}
First change that should be done is, rename your function name, as close is a keyword in Javascript.
Second one is that, document.getElementsByClassName() returns an array and thus to get the first element you should use the index position 0.
According to the docs
The Element.getElementsByClassName() method returns a live
HTMLCollection containing all child elements which have all of the
given class names. When called on the document object, the complete
document is searched, including the root node.
Read more about it here
You can use Jquery
<div class="box">Hide on button click!!
<button class="close">Close</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".close").click(function(){
$(this).parent().hide(); return false;
});
});
</script>
Check this fiddle
You can also do this easily with jQuery.
$("#hide").click(function(){
$(".box").fadeOut(150);
});
just brushing up on my javascript skills and trying to figure out why getElementsByClass isn't working for my code. The code is pretty simple. Upon clicking a button "clicky", the script will create a child h1 element of div. It works perfectly fine when I use getElementById and changing the div class to Id but doesn't work when I change it to class.
I've tried, getElementsByClassName, getElementsByClass, getElementsByTagName and changing the div to the appropriate attribute but no luck.
<!doctype html>
<html>
<body>
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky </button>
<script>
function myFunction(){
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.getElementsByName("thistime").appendChild(first);
}
</script>
<div class="thistime">Hi</div>
</body>
</html>
You need to update your code from
document.getElementsByName("thistime").appendChild(first);
to
document.getElementsByClassName("thistime")[0].appendChild(first);
For reference - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Working code - http://plnkr.co/edit/k8ZnPFKYKScn8iYiZQk0?p=preview
You could use getElementsByClassName(), which is supported in IE9+:
document.getElementsByClassName("thistime")[0].appendChild(first);
But a better alternative may be querySelector(), which is supported in IE8+
document.querySelector(".thistime").appendChild(first);
Note that querySelector() uses CSS selector syntax, so you should place a dot (.) before the class.
Snippet:
function myFunction() {
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);
document.querySelector(".thistime").appendChild(first);
}
<p>Click on button to see how appendChild works</p>
<button onclick="myFunction()">Clicky</button>
<div class="thistime">Hi</div>
As you have noticed, the function is called getElementsByName with "elements" being a plural.
It returns a list of markups by their name (and not their css class).
You need to use the function that handles the class name, and get the first element of the array, or loop on all the results, depending on what you are looking for.
I have a set a dynamically created divs with the same class name. Now I want to append a entirely new div to all of the above mentioned divs.
Say the class name is extra-upper-block
At the end of my page I have this code
<script>
//function call to load dynamic content
</script>
<script>
$('.extra-upper-block').append('<div>New Div</div>');
</script>
This throws an error in chrome's console
Uncaught TypeError: undefined is not a function
But when this code is executed in chrome's console after the page is loaded, it works!
Why doesn't it work even when I load the dynamic content before executing the append command. Help?
Use jQuery class selector.
$(document).ready(function(){
$('.extra-upper-block').append('<div>New Div</div>');
});
Wrap your code in $(document).ready() for jQuery to get the elements available, and include jQuery file reference.
Note : .append() method is a part of jQuery.
Demo
document.getElementsByClassName returns an array-like object, you can't use it like jQuery, you need to access the individual element in a loop. Also, use appendChild on DOM elements, because they don't have an append method (like jQuery does).
Also, you are trying to append a string <div>New div</div>, you can't directly do that with a DOM element, so instead you can create the div element like so:
Demo
var elements = document.getElementsByClassName('extra-upper-block');
for(var i=0; i<elements.length; i++){
var newDiv = document.createElement('div');
newDiv.appendChild(document.createTextNode('New div'));
elements[i].appendChild(newDiv);
}
Note: querySelectorAll has better cross browser support than this. If you have jQuery included you can simply do:
$('extra-upper-block').append('<div>New Div</div>');
As you can see, with jQuery you can append a string directly.
try writing
document.getElementsByClassName('extra-upper-block')[0].appendChild(document.createElement('div'));
Append is a function in jQuery, try this:
<script>
$(function() {
$('.extra-upper-block').append('<div>New Div</div>');
});
</script>
I am creating a variable that stores an elements ID in the variable. I could write it like this:
var webappData = document.getElementById('web-app-data');
If I wanted to do the same using jQuery I think I would write it like this:
var webappData = $('#web-app-data');
However, when I try that it doesn't work. (Script throws an error because the variable isn't selecting the div with that Id.)
How would I use jQuery to select an element and store it in a variable?
document.getElementById('web-app-data') isn't the same as $('#web-app-data'). The later returns jQuery object, which is kind of an array of HTMLElement objects (only one in your case).
If you want to get HTMLElement, use $('#web-app-data')[0]. Check:
document.getElementById('web-app-data') === $('#web-app-data')[0]; // true
It's ok.. Maybe something else is wrong in your code..
Example:
<div id="web-app-data">
Hello
</div>
<script type='text/javascript'>
var webappData = $('#web-app-data');
alert(webappData.text()); // Hello
</script>
Fiddle
Above code should work just fine. Your problem might be, that jQuery doesn't find any corresponding elements from the DOM since the element has been removed or hasn't been loaded there yet. If you try to
console.log($('#web-app-data'));
that variable, you can check if jQuery actually found anything. jQuery object should have lenght of (atleast) one if corrensponding element is indeed in DOM atm.
That will work and you use just like it was the full JQuery selector.
var elm = $('#webappData');
if (elm.hasClass('someClass')) elm.removeClass('someClass');
return;