object HTMLcollection[0] keeps returning undefined - javascript

Suppose we have something like:
1
2
3
When I try something like
alert(document.getElementsByClassName("my-list"))
I get object HTMLCollection. And if I try something like alert(document.getElementsByClassName("my-list")[0]) I get undefined. How can I get the first href in the list? So it would be "1" in this case.

Check this in Fiddler. Place the document.getElementsByClassName("my-list") in a round bracket and the add the index [0] to it.
**UPDATE**: Use `window.onload` to perform operations after all DOM elements
are loaded.
window.onload = function()
{
alert((document.getElementsByClassName("my-list"))[0])
}
1
2
3

It could happen if you add the script in the HTML header. In this case, you saw HTMLCollection; however, the items would be empty.
move the script to the bottom of the HTML body.

Also, just be sure to check your code, I had this problem from using querySelector. If you use querySelector it only returns one element (which will return undefined when iterating), while querySelectorAll creates a html collection which you can iterate through.

Related

textContent returns undefined

I have a table in which I want to extract the text of the active item. I do this with the following code:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
console.log(addedWorkout);
addedWorkout = addedWorkout.textContent;
console.log(addedWorkout);
The problem is that I keep getting undefined. I checked the console and it indeed finds the element I want without fail.
I am relatively new to Javascript, but after over an hour of Googling I could not find the issue and I don't understand why. I know that I can get the text element if I hardcore it using the following line:
document.querySelector("#selectiona1").textContent
but not with:
$("#selectiona1").textContent
What is the difference between these 2? I read that textContent is part of the DOM, to my understanding it relates to objects and according to my console i think it is an object. I made some crazy attempts like putting the object I got into the querySelector, but nothing works.
With this line:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
you're using jQuery to select the .dropdown-item.active inside #custDropDownMenuA, and when you select with jQuery, you get a jQuery object in response. So, addedWorkout is a jQuery object, and jQuery objects generally do not have the same properties/methods as standard HTMLElements. (querySelector is the vanilla Javascript method to retrieve an element)
Either select the [0]th item in the jQuery collection to get to the first matching element:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active")[0];
Or use the jQuery method to get the text of the first matching element, which is .text():
var addedWorkoutText = addedWorkout.text();
(note the use of a new variable - you will likely find it easier to read and debug code when you create new variables rather than reassigning old ones, when possible)
Your var 'addedWorkout' is a Jquery object, not a html element.
To show the text use:
addedWorkout.text();
Alternatively, you can change the 'addedWorkout' to a html element by adding the index [0], like this:
addedWorkout[0].textContent;

Javascript return an empty array but with two elements in it

I am little confused. When i try to get elements like document.getElementsByClassName('html5gallery-tn-image-0') what i get is that:
These are the elements i am searching for but instead the array says that it is empty. Can you explain me please why is that way and can i reach the elements in this array? Thank you in advance!
You have several things going on that explains this behaviour:
You are performing the console.log at a moment that there are no such elements yet in the document. Probably the JavaScript executes before the document is ready. This explains why temp[0] is undefined.
The HTMLCollection returned by getElementsByClassName is not an array and has some magical behaviour: it is a live collection. So if the document gets an additional element of that class, it will magically appear in that temp collection without you touching it!
When you log an object to console, the Chrome dev tools will not collect all the object properties at that moment, but asynchronously. This means that although at the time of logging the collection was empty, it no longer is when you click on the dev tools to see what is in the collection.
See the first two points illustrated in this script:
var temp = document.getElementsByClassName('html5gallery-tn-image-0');
console.log(temp.length); // 0
// add the class to the element
mydiv.className = "html5gallery-tn-image-0";
console.log(temp.length); // 1
<div id="mydiv"></div>
Solution
Move your JavaScript code so that it only executes when the document is completely loaded. Either:
Move your Javascript to the end of the body tag, or
wrap the code in a document.addEventListener('DOMContentLoaded', function () { ... }); callback.
In your console.log it returns with two image elements on it, so it not empty.
getElementsByClassName returns a HTMLCollection, which has a few special properties. One of them is, that the content of that array-like thing gets updated as soon as the DOM gets updated. Additionally in Chrome the part which shows "[]" got calculated as soon as you pressed enter, but the content (those two elements) get evaluated only when you expand the output.

How do I find out whether an element with that ID exists or not?

I do a:
console.log($('#test'));
I know that test doesn't exist. If I do a console.log, it doesn't output undefined/null. Rather it ouputs something like an empty array and when I check that array it looks like it returns the jQuery object itself.
I also tried:
if ($('#test')){
//do something
}
But it still doesn't work. I want to know whether the ID I am selecting exists on page or not. How do I do that using jQuery?
It's something like 20x faster to do this:
if (document.getElementById("test"))
compared to the jQuery operation to just determine if a DOM object with that id exists in the page. jQuery can do a lot for you, but when its general selector engine and general object structure isn't needed, it's not the quickest way to do things.
As others have said, $("#test") is always a valid jQuery object, even if #testdoesn't exist. If the #test object doesn't exist, then $("#test") will be a jQuery object that has no DOM objects in it (the internal array will have a .length === 0), but it's still a valid object.
In JavaScript, objects are always truthy, so using it in that fashion will always pass the condition.
You need to check the length property. A response of 0 is falsy, and will work as expected.
if ($('#test').length) {
// ...
}
This is unlike document.getElementById(), which returns null if the element with that id attribute does not exist.
If this is confusing, you could always write a quick jQuery plugin.
$.fn.exists = function() {
return !!this.length;
};
You can then call exists() on a jQuery collection, to ensure that selector has matched at least one item.
Use '(' and ')' for 'if' statements, and check if the returned array has length greater than 0:
if ($('#test').length > 0){
//do something
}
use something like this
if ($('#test').length > 0){
alert('hi')
}else
{
alert('hello')
}
Live Demo ​
Use
if ($('#test').length > 0){
//do something
}
the length tells you how many items were selected if it is 0 no element has the id test.
best way for this is to check length of the selected element
if ($('#test').length > 0){
//do something
}
But if you want to create a exist function jQuery welcomes you just add the line in your script
jQuery.fn.exists = function(){return this.length>0;}
and now you can Check if element exist or not
if ($(selector).exists()) {
// Do something
}
console.log($('#test'));
This won't print the value because it represents the object found in the DOM with the id test.
If you want to get values, use $("#test").val(); or $("#test").html();
If you want to check existence, do the length test as suggested above.
Also, if you're testing for the existence of a generated element (something you added to the DOM), make sure you checkout .live (http://api.jquery.com/live/). This is need for all elements that are created after the page is loaded.

live function with out arguments in jQuery

I wanna select some item by jQuery which has been added after loading page,so I wanna use live() function.I used it before for clicking like following code:
$("selector").live('click')
but now when I wanna use it in another function.
but It will not work with out argument,like it live()
for e.g followin code will alert test (work)
var pos_eq=Math.abs($('.myList').css("left").replace("px","")/$('.myList').children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
but this will not.
var pos_eq=Math.abs($('.myList').live().css("left").replace("px","")/$('.myList').live().children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
how can I solve it?
You want a function, not a variable. It looks like you are trying to keep pos_eq up to date after elements have been added to the page. Having a variable auto-update when the DOM changes in the way you are trying to do is not possible with JavaScript. What you can do is use a function instead of a variable. This way whenever the value is accessed you are getting the latest value because it is computed on demand:
function pos_eq() {
var list = $('.myList');
var left = parseInt(list.css("left"));
var width = parseInt(list.children('li').eq(0).css('width'));
return Math.abs(left / width) + 1;
}
I broke your code up into multiple statements to make it more readable. You would use this function the same as you used the variable, but instead add parens to the end to invoke the function:
alert(pos_eq);
alert(pos_eq());
To get a set of objects at the time you need them, just do $("selector"). That will do a query at that time and get the set of objects. There is no need to use .live() in order to query objects on the page. It does not matter whether the objects were part of the original page or were added dynamically later. When you do $("selector"), it will search the contents of the current page and get you the objects that are currently in the page that match the selector.
There is no way to do a live selector query and save it and have it automatically update in jQuery or any other library I know of. The way you solve that issue with a dynamic page is that you just do a new query when you need current results.
The description of live() is: Attach a handler to the event for all elements which match the current selector, now and in the future. It does not give you a live node list despite its name. jQuery does not have any method that returns a live node list(such as those returned by getElementsByTagName etc.) as far as I know.

bookmarklet: inserting text into textarea with js?

What I am doing wrong?
javascript:document.getElementsByTagName('textarea').innerHTML='inserted';
I want to create a bookmarklet to insert simple text to a textarea on a given webpage.
Use the value property rather than innerHTML and make sure your code evaluates to undefined, which you can do by wrapping it in a function with no return statement. If you don't do this, the contents of the page will be replaced with whatever your code evaluates to (in this case, the string 'inserted').
javascript:(function() {document.getElementsByTagName('textarea')[0].value = 'inserted';})();
Update 14 January 2012
I failed to spot the fact that the original code was treating document.getElementsByTagName('textarea') as a single element rather than the NodeList it is, so I've updated my code with [0]. #streetpc's answer explains this in more detail.
Unlinke getElementById, getElementsByTagName has an sat Elements because it returns an array array-like NodeList of the matching elements. So you'll have to access one of the elements first, let's say the first one for simplicity:
javascript:void((function(){document.getElementsByTagName('textarea')[0].value='inserted'})())
Also, as mentioned by others, value property rather than innerHTML here.
In case anyone wonders how to use the currently focused text field, use the following:
document.activeElement.value = "...";
In jQuery you have to use if this way:
for single element -> $('#element_id').html('your html here')
for all text areas -> $('textarea').val('your html here')
I have to confess that I`m not sure why it works this way but it works. And use rameworks, they will save you time and nerves.

Categories

Resources