How to get number of element ref by id using javascript? - javascript

How to get number of element by id using javascript ?
http://jsfiddle.net/3AaAx/51/
normally, after load page , it's will alert 2 (length of element id ele1).
But why alert undefined
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="ele1" class="test" value="test">
<input type="text" id="ele1" class="test" value="test">
<script>
$(function() {
//var xxx = document.getElementsByClassName('test');
var xxx = document.getElementById('ele1');
var xxx;
alert(xxx.length);
});
</script>

getElementById() returns just an element. A single element has no property length. (There may be exceptions, but in general ... Even if there is a length property it most likely does not refer to the amount of elements returned.)
You probably refer to the getElementsBy...() (note the s!) or querySelectorAll() functions, which return a NodeList, which has a length property.

This is how you get the number of elements returned by getElementById:
var xxx = (document.getElementById('ele1') === null) ? 0 : 1;
getElementById returns null if no element matched the id. If the function does not return null, then one and only one element matches the criteria. See more here.

The line you commented off is right:
//var xxx = document.getElementsByClassName('test');
getElementsByClassName returns a collection of DOM elements, which does have a length property. Note in this method Elements is plural form. length indicates the amount of elements in the collection.
However you misunderstand getElementById. This method will only return a DOM element (or null if there isn't such element). Note in this method Element is singular form. A DOM element doesn't have a length property usually.
Another problem in your code, ID should be unique within a page. If you have two or more elements with the same ID, that's illegal markup. In such case you will get unexpected result.

Related

TypeError: document.getElementsByTagName(...).className is undefined

I keep getting
TypeError: document.getElementsByTagName(...).className is undefined
What's up with that, I don't really get it.
function test(){
if ( document.getElementsByTagName("body").className.match(/(?:^|\s)test(?!\S)/) ){
document.getElementsByTagName("body").className += " test";
alert("test");
}
}
document.onload = test();
Note that it's getElementsByTagName, not getElementByTagName -- it's plural. It returns a list of elements.
To add a class to the first element in that list:
if ( document.getElementsByTagName("body")[0].className.match(/(?:^|\s)test(?!\S)/) ){
document.getElementsByTagName("body")[0].className += " test";
alert("test");
}
getElementsByTagName returns an array of elements of psecified tag. For example, if you have 100500 div elements on your page getElementsByTagName will return an array with length of 100500 and it will contain all your div elements. And of course, array has not property className
If you want to select only one specific element you can specify an id attribute for it and call getElementById which returns you single element
In case of using getElementsByTagName you can try to get array of your elements, select the first item from it (zero index) and then read its' className property

Call an array whose value is between quotes: getElementById("'"+CB[x]+"'")

I need to call either a array like below:
ONone = document.getElementById("'"+CB[x]+"'");
or a property value like so:
var ONone = document.getElementById("'"+animateSector.named.id+"'");
the above values i.e (CB[x] and animateSector.named.id) alert the value that i need however when there called in the
(document.getElementById("'"+CB[x]+"'")
and
(document.getElementById("'"+animateSector.named.id+"'")
they return a null console error saying
Onone is null
getElementById doesn't accept a CSS selector, it accepts an ID. So even if the id would need to be quoted in CSS, it doesn't matter, because this isn't CSS.
Without seeing your HTML it's impossible to be sure, but:
Get the element whose id is whatever is in CB[x], or whatever is in animateSector.named.id:
ONone = document.getElementById(CB[x]);
ONone = document.getElementById(animateSector.named.id);
Get the element whose id is CB[x]:
ONone = document.getElementById('CB[x]');
Get a list of elements whose name is CB[], and then get entry #x from that list:
list = document.querySelectorAll('[name="CB[]"]');
entryX = list[x];
querySelectorAll, as the name implies, does accept a CSS selector, and returns all matching elements in a list.

What does getElementsByName("secilenil")[0] mean?

var sec = document.getElementsByName("secilenil")[0];
I did not understand the end of this statement which is [0].What does this mean? "secilenil" is the name of select element.
getElementsByName returns a NodeList of all elements with a name attribute equal to secilenil. Using [0] selects the first found node.
The [0] notation is similar to that of an array - it means you want to extract the element at the specific index.
MDN reference.

How to chain getElementById and getElementByClassName

I have a div with id "productPriceContainer" and within this div a class "price".
I want to access the innerHTML of class "price" since I have other classes called "price" as well.
Can I chain something like this?
document.getElementById(productPriceContainer).getElementsByClassName(price).innerHTML
If not what is the correct way of doing what I need?
Thanks
If you have one element with class price in the element with id productPriceContainer, you can do
document.getElementById('productPriceContainer')
.getElementsByClassName('price')[0].innerHTML
Notice the s in getElementsByClassName. It explains why you can't chain just like that. You don't have a function called getElementByClassName because, contrary to the id, there is no unicity of elements having a given class.
Almost.
If you want to pass strings, then you have to pass strings and not undefined variables
getElementsByClassName (plural!) returns a NodeList, not a Node, so you have to loop over it to get the Nodes (on which you can then use innerHTML.
You are passing a variable, not a String to the method -> it should be "price" not price.
The Method for retrieving Nodes by a classname is getElementsByClassName you were missing the "s"
It returns an Array of DOM Elements so you have to iterate over the childs of your container
For example:
document.getElementById("productPriceContainer").getElementsByClassName("price")[0].innerHTML = "Asdf";
sets the innerHTML of the first DOM element with the class "price" within your container Element to "Asdf"
Iterating over the Elements could look like this:
var elements = document.getElementById("productPriceContainer")
if(elements) {
var classes = elements.getElementsByClassName("price");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "Asdf" + i;
}
}
Here is a JSBin

Select all ID's or Class's with getElementBy

I have a script that I'm running and I want to it to select all the ID's or Class's instead of just the first one.
<script type = "text/Javascript" >
function color(){
var d=document.getElementsByClassName("black")[0];
d.setAttribute("style", "background-color:#333;");
}
</script>
The [0] in document.getElementsByClassName("black")[0] means that you're actually discarding all but the first, after selecting them. Use a loop if you want to iterate over the value returned by gEBCN.
Use document.getElementsByTagName('*') if you want all elements.
function color() {
var allElements = document.getElementsByTagName('*');
for (var i=0; i<allElements.length; i++) {
allElements[i].setAttribute('style', 'background-color:#333;');
}
}
To get all the elements with a certain ID, you can rely on querySelectorAll, as in
var d = document.querySelectorAll("#temp");
Keep in mind some things:
It's semantically wrong, even if not syntactically, to have multiple elements with the same id.
querySelectorAll return a NodeList object, not a live collection. This means that if you add another element with id "temp", that won't be in the collection you got and you have to call querySelectorAll again.
querySelectorAll isn't supported by IE7 and previous versions.
You already have an answer for getElementsByClassName.

Categories