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

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.

Related

JSON.stringify gives something completely different

var tempid = document.getElementById("TDID1");
Using alert(JSON.stringify(tempid)) Gives
{"jQuery3600419938127216425761":{"events":{"click":[{"type":"click","origType":"click","data":null,"guid":14,"namespace":""}]}}}
When all i want it to give is a variable typeof sting with document.getElementById("TDID1")
JSON.stringify creates a string for the value you give it. When that value is an object, the string is JSON describing all of the own, enumerable properties of the object.
In your case, the object is a DOM element, and one on which jQuery has been used at some point.
When all i want it to give is a variable typeof sting with document.getElementById("TDID1")
If I understand you correctly, that's not what JSON.stringify is for. You could write the string directly of course:
const str = 'document.getElementById("TDID1")';
...but there's no way, starting from the value returned by getElementById, to construct a string for the way you accessed that value.
Or if you want the value of that element (assuming it's an input or select element), you could get that value from .value:
const value = document.getElementById("TDID1").value;
Or if you want the text content of a non-input element:
const text = document.getElementById("TDID1").textContent;
Or if you want the inner HTML of the element:
const html = document.getElementById("TDID1").innerHTML;
Or the outer HTML of the element:
const html = document.getElementById("TDID1").outerHTML;

How to check if element name contains the given string

In the code below I`m checking if these 2 elements exist.
const var1 = form.elements[elemName1] ||
form.elements[elemName2]
if(var1){
doSmth
}
But what I need is to check if element's name contains a certain string.
Like:
const var1 = form.elements[NameContains(givenString)] ||
form.elements[NameContains(givenString)]
I tried to find the needed syntax in google bud did not succeeded.
You can use an attribute contains selector (*=) with querySelector (to find the first) or querySelectorAll (to get a list of matches).
For instance:
const var1 = form.querySelector("[name*=foo]");
finds the first element in form whose name attribute contains the substring foo. Similarly there's ^= for "starts with" and $= for "ends with."
If you're checking for two different substrings, either use a selector group:
const var1 = form.querySelector("[name*=foo], [name*=bar]");
or two calls:
const var1 = form.querySelector("[name*=foo]") || form.querySelector("[name*=bar]");
The difference between those is that the selector group will find the first matching element in document order, whether it's a foo or bar element. The second will look for a foo element first, and only look for a bar element if no foo is found.

Inconsistant JavaScript Return Values

Why does getElementById() return null if the ID doesn't exist and getElementsByClassName() returns undefined if the class doesn't exist? This seems like an inconsistency in the JavaScript language since both are DOM methods. For example:
console.log( document.getElementById('bogusID') ); // null
console.log( document.getElementsByClassName('bogusClass')[0] ); // undefined
I recently had to find out the hard way, having my program crash since I wrongly assumed both methods would return "undefined" on a fail.
Is there actually a reason for the different return values?
document.getElementsByClassName('bogusClass') returns an empty array and you are trying to access the zeroth element, which doesn't exist, so you get undefined.
Javascript, unlike other programming language doesn't throw index out of range exception, because indexes are implemented as properties and accessing a property which doesn't exists returns undefined.
In terms of checking and handling for null and undefined, both are falsy value in javascript and hence your code should be the same for both cases.
if(condition){
// Both undefined and null would not pass the condition.
}
console.log( document.getElementById('bogusID') ); // null
Thats because there aren't bogusID items on your DOM so the return is null
console.log( document.getElementsByClassName('bogusClass')[0] ); // undefined
Thats because your getting the index 0 of an array that doesn't have an element at the 0 pointer. So the index 0 of the array isn't defined (undefined)
I don't know how the program is defined internally for getElementById() & getElementByClass but according to mozilla documentation getElementById() basically returns a reference(object) to the element.
ID
eg: element = document.getElementById()
Return Value
element -
is a reference to an Element object, or null if an element with the specified ID is not in the document. In dom there should be only 1 ID with a same name so there is no reuse in ID name.
Class
eg: var elements = element.getElementsByClassName(names);
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.
In dom there should be only 1 ID with a same name so there is no reuse in ID name and also HTMLCollection uses array to collect all the elements that are refered using classname.
Undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Use key as ID to write text to paragraph

I am trying to do a each loop and generate the class names to write the text stored in the array dynamically instead of doing them one by one. Nothing seems to write to the paragraphs though?
var user = {};
user['fname'] = 'Hello';
user['lname'] = 'World';
$.each(user, function(key, value) {
$('p').hasClass(key).text(value);
});
.hasClass() returns a boolean. It returns whether any of the elements in the collection have that class.
What you want to do is create a selector that searches for that class. Something like this:
$('p').filter('.'+key).text(value);
Or even this:
$('p.'+key).text(value);

How to get number of element ref by id using 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.

Categories