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
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');
if I use
var temp = document.querySelectorAll(".class");
for (var i=0, max=temp.length; i<max; i++) {
temp[i].className = "new_class";
}
everything works fine. All nodes change their classes.
But, with gEBCN:
var temp = document.getElementsByClassName("class");
for (var i=0, max=temp.length; i<max; i++) {
temp[i].className = "new_class";
}
I get error. Code jumps out of the loop at some point, not finishing the job with msg "can't set className of null".
I understand that this is static vs live nodelist problem (I think), but since gEBCN is much faster and I need to traverse through huge list of nodes (tree), I would really like to use getElementsByClassName.
Is there anything I can do to stick with gEBCN and not being forced to use querySelectorAll?
That's because HTMLCollection returned by getElementsByClassName is live.
That means that if you add "class" to some element's classList, it will magically appear in temp.
The oposite is also true: if you remove the "class" class of an element inside temp, it will no longer be there.
Therefore, changing the classes reindexes the collection and changes its length. So the problem is that you iterate it catching its length beforehand, and without taking into account the changes of the indices.
To avoid this problem, you can:
Use a non live collection. For example,
var temp = document.querySelectorAll(".class");
Convert the live HTMLCollection to an array. For example, with one of these
temp = [].slice.call(temp);
temp = Array.from(temp); // EcmaScript 6
Iterate backwards. For example, see #Quentin's answer.
Take into account the changes of the indices. For example,
for (var i=0; i<temp.length; ++i) {
temp[i].className = "new_class";
--i; // Subtract 1 each time you remove an element from the collection
}
while(temp.length) {
temp[0].className = "new_class";
}
Loop over the list backwards, then elements will vanish from the end (where you aren't looking any more).
for (var i = temp.length - 1; i >= 0; i--) {
temp[i].className = "new_class";
}
Note, however, that IE 8 supports querySelectorAll but not getElementsByClassName, so you might want to prefer querySelectorAll for better browser support.
Alternatively, don't remove the existing class:
for (var i=0, max=temp.length; i<max; i++) {
temp[i].className += " new_class";
}
I have a website I am working on that takes input from the user and calculates a results. All of the forms are html text input forms where they enter in certain number.
I want to use the input event to check for when the user enters a new value in one of these 6 text forms. The example in the book I am using, JavaScript and JQuery: Interactive Front-End Web Development, suggest to use the getElementById method with the dom event handler to do this:
For example:
function doWhatIwantToDo()
{
//Do something
}
var el = document.getElementById('username');
el.oninput = doWhatIwantToDo;
This is great and I could set up 6 unique ids for each text form, which I will need to do anyway in order to change their inner html in my javascript code, but is there someway I can check for input by using a class name?
I tried using getElementsByClassName but it is tripping me up because it returns an array of objects.
I want to avoid any jquery solutions right now because I am trying to learn vanilla javascript only right now.
Edit/Results:
I like "acbabis" and "mohamedrias" answers but the book implies that using Event Listeners is a newer method and not supported by all browsers. So for now, I would like to stick with the Traditional Dom Event Handlers that it talks about.
"dandavis" answer to just do it in a loop made me realize that perhaps binding an element to an event handler, in a loop, SHOULD actually work and that perhaps I was making a mistake in my loop.
I checked and stupidly I wasn't using array notation to loop through each object in the returned array which is why nothing was happening. Here is my final code that works:
var test = document.getElementsByClassName("test");
for (var i=0; i < test.length; i++)
{
console.log( test[i] );
test[i].onclick = testiness;
}
function testiness ()
{
alert("Success!");
}
var inputElements = document.querySelectorAll('.className');
for(var i = 0, len = inputElements.length ; i < len ; i++) {
inputElements[i].addEventListener('input', doSomethingFunction);
}
querySelectorAll returns you a static NodeList. You need to iterate and attach the event.
Instead of using getElementsByClassName which returns a live HTMLCollection, working with querySelectorAll would be preferrable.
I would document.querySelectorAll for this.
var inputs = document.querySelectorAll('input');
for(var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('input', doWhatIWantToDo);
}
This will find all input elements on the page and add the handler to each one. If you want to use a class, just add it to the desired input tags, and replace document.querySelectorAll('input') with document.querySelectorAll('input.classname').
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;
Howdy guys.
I am wondering why does the following code snippet work (tested in the latest Firefox Nightly):
var links = document.querySelectorAll('a[href]');
for (var i = 0; i < links.length; ++i) {
console.log(links[i].search); // Where does `search` come from?
}
As “usual,” I get the query string of the href in each a element (something I can also do with a simple substr or something, but that's not the point); whereas, if I do something like this:
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; ++i) {
console.log(divs[i].search);
}
All I get is undefined.
According to MDN, there is no such thing as search property available for element objects (document.querySelectorAll(selector) returns a non-live NodeList of element objects). So, where does all this come from?
Any help would be greatly appreciated.
Different sorts of HTML element nodes in the DOM have different APIs. The nodes corresponding to <a> tags implement an API for examining URLs. The "search" property is one of those special type-specific things. Basically an <a> node has the same properties as window.location, more or less.