I want to get the selected index from a getElementByClassName.
I know how can I get it from Id but somehow its not working for ClassName..
document.getElementById("Metriclayer").selectedIndex = abc;
like this how can I get it for document.getElementByClassName.
I want to set the value of abc( its an integer) in the selected index of document.getElementByClassName("MetricClass").
How can I do that .
There is no function getElementByClassName, the function is getElementsByClassName. As you can see, Elements is plural, so it returns a collection of all elements with that class, not a single element. You need to index the collection. If you want the first (or only) element of the collection, use:
document.getElementsByClassName("MetricClass")[0].selectedIndex = abc;
DEMO
If you want to operate on all of them, write a loop:
var elements = document.getElementsByClassName("MetricClass");
for (var i = 0, l = elements.length; i < l; i++) {
elements[i].selectedIndex = abc;
}
document.getElementByClassName does not exist, since it would be pointless - there can be zero-to-many elements with the same class name in a single document. The correct plural function name is document.getElementsByClassName. Since this returns an array of elements, not a single one, more processing is required to get a useful result.
Try this out:
var el = document.getElementsByClassName('MetricClass');
var index0 = el[0].selectedIndex;
Related
I'm not exactly sure how to word this, but I am using Javascript to change text. I am using Javascript on the site Quizlet. As you can see, there are two columns: terms and definitions. As of now, the script changes both when I only want it to change the term list. Here's a video, too: https://drive.google.com/file/d/1ly3askpLQjzXeCMx9Mk9iVpSEXCw6i25/view
Works, but changes both:
var myClasses = document.getElementsByClassName("ProseMirror");
for (var i = 0; i < myClasses.length; i++) {
myClasses[i].innerHTML = "new content";
}
I tried this, but it didn't work:
var myClasses = document.getElementsByClassName("WordList");.document.getElementsByClassName("ProseMirror");
for (var i = 0; i < myClasses.length; i++) {
myClasses[i].innerHTML = "new content";
}
If you're trying to find a .ProseMirror element only when it's inside a .WordList element, you can use a CSS selector for that with querySelector:
const element = doucment.querySelector(".WordList .ProseMirror");
element.innerHTML = "new content";
That finds the first element with the class ProseMirror that's also inside an element with class WordList.
I don't think you want a list of matches, but if you did, you'd use querySelectorAll (which returns a NodeList of all matches) instead of querySelector (which returns the first matching element).
You can use document.querySelectorAll to get the elements with multiple classes.
document.querySelectorAll('.WordList.ProseMirror');
I attached a codepen example : http://codepen.io/anon/pen/zpmjJ
I just try to change the classname of an html collection array with a classic loop and after many test i can't figure out whats wrong and if i made a common mistake, i have always one item ignored.
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
bout.addEventListener("click",function(){
var newtest = document.getElementsByClassName('test');
for (i=0; i < newtest.length; i++)
{
newtest[i].className="bob";
}
});
The problem here is that you are using document.getElementsByClassName which gives you a live NodeList. You should use document.querySelectorAll('.test') instead.
var newtest = document.querySelectorAll('.test');
for (var i=0; i < newtest.length; i++) {
newtest[i].className = "bob";
}
With live NodeList collection newtest is a reference to a dynamically updated collection of elements (indexed by className test). So after the first loop iteration when you overwrite className with bob the whole collection becomes smaller by one (because newtest[0] no longer has class test). It makes indices shift.
One more problem with your code: don't forget var keywords.
Demo: http://codepen.io/anon/pen/BAFyb
getElementsByClassName is live selector, so when you change something that not matching this selector, it will remove element from scope. So at first iteration it has 3 elements, but when you change class, it remove one element and you leave with 2 elements, so on next iteration it will take i element which is i=1 so it will take second element from top. That's why you get always 1 missing. You may use newtest[0].className="bob"; to loop through, but when you will reach last element, it will be single element, not array any more, so you need to use newtest.className="bob"; for last one
I want to add a functionality on click event.
I want to display none four div but this code seems doesn't work for me
Please tell me the mistake in this
<a class="lightbox-close" href="#" onclick="document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4').style.display = 'none';"></a>
The querySelectorAll returns a NodeList, you need to iterate over it and set the properties.
So it will be better to write a separate function where you can write the iteration logic
var els = document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4');
for (var i = 0; i < els.length; i++) {
els[i].style.display = 'none';
}
Query selector is not like jQuery selector where you can do
$('#goofy_1,#goofy_2,#goofy_3,#goofy_4')// it will get you all div selected
Instead Query selector returns nodeList which means you are getting
try console log your querySelectorAll
console.log( querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4'));
you will get something like
i.e i am selecting a
now you can see that there isnt single element selected so you can directly make any changes
Now you need to loop through all element like Arun P Johny telling
var allElements = document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4');
for (var i = 0; i < els.length; i++) {
allElements [i].style.display = 'none';
}
Good Read
Difference between HTMLCollection, NodeLists, and arrays of objects
I attached a codepen example : http://codepen.io/anon/pen/zpmjJ
I just try to change the classname of an html collection array with a classic loop and after many test i can't figure out whats wrong and if i made a common mistake, i have always one item ignored.
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
bout.addEventListener("click",function(){
var newtest = document.getElementsByClassName('test');
for (i=0; i < newtest.length; i++)
{
newtest[i].className="bob";
}
});
The problem here is that you are using document.getElementsByClassName which gives you a live NodeList. You should use document.querySelectorAll('.test') instead.
var newtest = document.querySelectorAll('.test');
for (var i=0; i < newtest.length; i++) {
newtest[i].className = "bob";
}
With live NodeList collection newtest is a reference to a dynamically updated collection of elements (indexed by className test). So after the first loop iteration when you overwrite className with bob the whole collection becomes smaller by one (because newtest[0] no longer has class test). It makes indices shift.
One more problem with your code: don't forget var keywords.
Demo: http://codepen.io/anon/pen/BAFyb
getElementsByClassName is live selector, so when you change something that not matching this selector, it will remove element from scope. So at first iteration it has 3 elements, but when you change class, it remove one element and you leave with 2 elements, so on next iteration it will take i element which is i=1 so it will take second element from top. That's why you get always 1 missing. You may use newtest[0].className="bob"; to loop through, but when you will reach last element, it will be single element, not array any more, so you need to use newtest.className="bob"; for last one
Ok to start of i currently have 4 divs with the same id for example:
<div id='name'></div>
<div id='name'></div>
<div id='name'></div>
<div id='name'></div>
and im currently using a javascript function to display the value of the div's for example:
function divCheck(){
alert(document.getElementById('name').innerHTML);
}
the problem im having is when i call the function it only displays the value of the first div.
My goal is to display the values of all the divs and place it into a Textarea input.
I will really truly appreciate it. In advance thank you.
Use class instead of id, and use getElementsByClassName
ID is for use once, and is generally for large item (div etc) which has to be pretty unique, or is to be individually accessed, when you need to access combinations or even apply CSS properties on grpups of html elements without having to type them again and for each id, use class, and apply the common properties to that class, use ID for unique properties.
Similarly here use class, as you can see the function is get*Elements*ByClassName, means it returns a group, and this is what class is for. For this kind of use, use class instead of ID.
As others have said, use classes instead of ids. Each id must be unique. You cannot have more than one object with the same id. Here's how it looks with a class name instead:
<div class='name'></div>
<div class='name'></div>
<div class='name'></div>
<div class='name'></div>
And, here's how you get all objects with a given class name and iterate over them:
function divCheck() {
var elems = document.getElementsByClassName('name');
for (var i = 0; i < elems.length; i++) {
alert(elems[i].innerHTML);
}
}
Unfortunately, getElementsByClassName() was not supported by IE until IE9 so you will have to use a javascript shim that implements it a different way when it doesn't already exist. Or, use a pre-built library like Sizzle or jQuery that already support this type of functionality in older browsers.
Hey why don't you use the class instead of Ids. Give dynamic classNames like class="className-'+id+'"
And the call them using :
$('div[class^="className-'+id+'""]')
Hope it will be useful.
P.S Avoid using same ids for elements.
Since you seem to be after a getElementsByClassName function independant of any library, try the following. It tries querySelectorAll first, if not available it tries getElementsByClassName, and finally does an old school iterate over elements approach.
It will also accept multiple class names and always returns a static NodeList or array of the matched elements (per querySelectorAll). Note that getElemensByClassName returns a live NodeList, so the result must be converted to an array otherwise it might behave a little differently if elements are being added or removed from the document.
/*
Selector must be per CSS period notation, using attribute notation
(i.e. [class~=cName]) won't work for non qSA browsers:
single class: .cName
multiple class: .cName0.cName1.cName2
If no root element provided, use document
First tries querySelectorAll,
If not available replaces periods '.' with spaces
and tries host getElementsByClassName
If not available, splits on spaces, builds a RegExp
for each class name, gets every element inside the
root and tests for each class.
Could remove duplicate class names for last method but
unlikely to occur so probably a waste of time.
Tested in:
Firefox 5.0 (qSA, gEBCN, old)
IE 8 (old method only, doesn't support qSA or gEBCN)
Chrome 14 (qSA, gEBCN, old)
*/
function getByClassName(cName, root) {
root = root || document;
var reClasses = [], classMatch;
var set = [], node, nodes;
// Use qSA if available, returns a static list
if (root.querySelectorAll) {
return root.querySelectorAll(cName);
}
// Replace '.' in selector with spaces and trim
// leading and trailing whitespace for following methods
cName = cName.replace(/\./g, ' ').replace(/^\s+/,'').replace(/\s+$/,'');
// Use gEBCN if available
if (root.getElementsByClassName) {
nodes = root.getElementsByClassName(cName);
// gEBCN usually returns a live list, make it static to be
// consistent with other methods
for (var i=0, iLen=nodes.length; i<iLen; i++) {
set[i] = nodes[i];
}
return set;
}
// Do it the long way... trim leading space also
nodes = root.getElementsByTagName('*');
cName = cName.split(/\s+/);
// Create a RegExp array of the class names to search on
// Could filter for dupes but unlikely to be worth it
for (var j = 0, jLen = cName.length; j < jLen; j++) {
reClasses[j] = new RegExp('(^|\\s+)' + cName[j] + '\\s+|$');
}
// Test each element for each class name
for (var m = 0, mLen = nodes.length; m < mLen; m++) {
node = nodes[m];
classMatch = true;
// Stop testing class names when get a match
for (var n = 0, nLen = reClasses.length; n < nLen && classMatch; n++) {
classMatch = node.className && reClasses[n].test(node.className);
}
if (classMatch) {
set.push(node);
}
}
return set;
}