Get all elements with the same class - javascript

I know that this:
document.getElementsByClassName('class-1')[0].
selects the first <div> that has the specify class.
I guess using a for() will get through the whole array of <div>.
Can somebody explain how to create that array ?
I will prefer plain Js.

Method getElementsByClassName() returns a set of DOM elements that have a certain class name. Here is a canonical example of how to use the returned list of nodes:
var elements = document.getElementsByClassName("class-1");
for (var i = 0, len = elements.length; i < len; i++) {
// elements[i].style ...
}

Related

How do I remove all style tags without jquery

Its simple, it removes all style tags on everything
This code below does exactly what I want to
$('*').removeAttr('style');
now I need to do the exact same thing without jquery, since my whole code is written
without jquery, I don't want to include the library for this simple task
among other things, this is what I tried so far but it won't work
document.getElementsByTagName('*').style.cssText = null;
document.getElementsByTagName('*').style.cssText = "";
document.getElementsByTagName('*').removeAttribute("style");
solution
var allstyles= document.getElementsByTagName('*');
for(var a=0; a<allstyles.length; a++)
{
allstyles[a].removeAttribute("style");
}
The document.getElementsByTagName('*') returns an array. You need to go through each item individually in a loop and remove the attribute.
An example of such a loop could be
var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++)
elements[i].removeAttribute("style");

Finding the index of the element with class in native Javascript

Is there a way to get the index of class name (I.e. the third element with the class "className" would be 3 without using jQ?
I don't know jQ, and I don't have time to learn it right now, and I don't want to include code into my code that I don't understand at least some.
Thanks.
BTW, I've used jQ instead of spelling it out so those results can be filtered out in Google should somebody have the same question. If I spelled it out, and somebody used the NOT operator in Google, this one would also disappear.
You could do something like:
// the element you're looking for
var target = document.getElementById("an-element");
// the collection you're looking in
var nodes = document.querySelectorAll(".yourclass");
var index = [].indexOf.call(nodes, target);
See: Array's indexOf.
If you have already a proper array as nodes instead of a NodeList, you can just do nodes.indexOf(target).
you can use document.getElementsByClassName
var el = document.getElementsByClassName('className');
for (var i = 0; i < el.length; i++) {
// your index is inside here
}
el[i] is the element in the current iteration, i is the index
(I.e. the third element with the class "className" would be 3)
if (i == 3)
return el[i]
JsFiddle: here.
Just use getElementsByClassName, it returns a list of elements with the specified classes.
elements = document.getElementsByClassName("test")
element = elements[2] //get the 3rd element
Hope this helps!
these work as of es6:
Array.from(document.querySelectorAll('.elements')).indexOf(anElement)
or
[...document.querySelectorAll('.elements')].indexOf(anElement)

Element ID from document.getElementsByClassName

Relatively new to JS/Ajax, so I may be missing something obvious here. Let's say at some point in javascript I run ajax to get a number of div elements with a certain class name. I then want to retrieve the html id tag from each of these elements and do something with that information (say populate the element), something like so.
var divstopop = document.getElementsByClassName("popField"),x;
for(x in divstopop){
divstopop[x].innerHTML= x.id; //x.id or something?
}
Is this in any way possible to do?
Using in is not how you should iterate over an array of elements. You should use the .length property and use numeric indexing:
for (var i = 0, n = divstopop.length; i < n; ++i) {
// get id property from element and set as innerHTML
divstopop[i].innerHTML = divstopop[i].id;
}

Executing a function to each item on a Nodelist in Javascript

I want to add an <img> to every <td> tag with a certain CSS Class in my page.
I used "querySelectorAll" to look them up, like this:
var painted = document.querySelectorAll('.painted');
Now I would like to add to each one of them a specific image with a unique ID. I assume I need to loop through the list somehow and edit each element's innerHTML, could anyone provide the syntax for that?
Thanks
Just run it like a normal for loop, and add properties to each element.
for (var i = 0, len = painted.length; i < len; i++) {
painted[i].id = "foo" + i;
painted[i].innerHTML = "<strong>Your content</strong>";
}
This uses innerHTML to create new content. If you need more complex content processing then there's no single syntax. You need to learn the DOM API and perform the needed manipulations.
For example, if you wanted to add an image, you can create one and append it directly.
for (var i = 0, len = painted.length; i < len; i++) {
var img = document.createElement("img");
img.id = "myimage" + i;
painted[i].appendChild(img);
}
Notice that I'm not using HTML markup. A DOM node doesn't have "HTML content". It is part of an object tree structure, so it has child nodes, which have their own child nodes, and so on.
So what you need to do, is perform some DOM selection with the current painted element as the root, and decide what should go where.

Get list of all input objects using JavaScript, without accessing a form object

I need to get all the input objects and manipulate the onclick param.
The following does the job for <a> links. Looking for something like this for input tags.
for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
var link = unescape(ls[i].href);
link = link.replace(/\\'/ig,"#");
if(ls[i].href.indexOf("javascript:") == -1)
{
ls[i].href = "javascript:LoadExtern(\\""+link+"\\",\\"ControlPanelContent\\",true,true);";
}
}
(See update at end of answer.)
You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it:
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
There I've used it on the document, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:
var container, inputs, index;
// Get the container element
container = document.getElementById('container');
// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
...but you've said you don't want to use the parent form, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).
Update: getElementsByTagName is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input elements?
That's where the useful querySelectorAll comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
You can also use it at the element level. For instance, if we have a div element in our element variable, we can find all of the spans with the class foo that are inside that div like this:
var fooSpans = element.querySelectorAll("span.foo");
querySelectorAll and its cousin querySelector (which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.
querySelectorAll returns a NodeList which has its own forEach method:
document.querySelectorAll('input').forEach( input => {
// ...
});
getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:
Array.from(document.getElementsByTagName('input')).forEach( input => {
// ...
});
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
// ...
}

Categories

Resources