Selecting all values inside an array - javascript

From what I understand, document.getElementsByClassName returns something like an array object.
How can I modify all returned objects without using jQuery?
Let's say I want to change border-color of all divs that have "class1" applied to them?
<div id="container">
<div class="class1">Hello</div>
<div class="class2">World</div>
<div class="class1">Hello</div>
<div class="class2">World</div>
</div>

Even jQuery will loop over the returned objects. Hiding the for (or while, each or map) loop is just syntax sugar but it's still a loop underneath it all:
var class1 = document.getElementsByClassName('class1');
for (var i = 0; i < class1.length; i++) {
class1[i].style.borderColor = 'green';
}

In one go === in one line?
[].forEach.call(document.getElementsByClassName("class1"), function(c) { c.style.borderColor = "red"; });

Related

Setting up a property inside function and call it back after Element get

In the example below, I have a function called color(). Is it possible to make it work as I would expect?
<div> text text </div>
<script>
function color(property) {
return this.style.color = property;
}
document.getElementsByTagName("div").color("red");
</script>
The code above gives me the error:
color(...) is not a function
There are two problems and an issue with that code:
getElementsByTagName returns a collection of elements, not just a single element. More here.
There's nothing that attaches the function color to an element or collection of elements.
To use this as the element, you'll need to make sure color is called in a special way.
Also note there's no need for the return in color.
If you want to apply the color function to all matching elements, you'll need a loop:
function color(property) {
this.style.color = property;
}
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; ++i) {
color.call(list[i], "red");
}
<div> text text </div>
But if you don't use this, the call is clearer:
function color(el, property) {
el.style.color = property;
}
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; ++i) {
color(list[i], "red");
}
<div> text text </div>
Note: You could add a property to the HTMLElement prototype (or even NodeList or HTMLCollection) so you could call color as a method, as you did in your question. That's probably not a good idea; if everyone did it, it would quickly lead to conflicts. Generally it's better to only modify the built-in DOM prototypes when applying a polyfill, but not for custom functions.

For loop only iterates once when trying to remove classes from elements

In Javascript I have a function that should find the elements on the page that have the "connected" class, and when a button is clicked the classes for these elements are cleared. I have written this code:
var prev_connected = document.getElementsByClassName("connected");
if (prev_connected.length > 0) {
for (var j = 0; j < prev_connected.length; j++) {
prev_connected[j].removeAttribute("class");
}
}
However, it only ever deletes the class attribute of the first "connected" element on the page. When I have two "connected" elements, I have confirmed that the "prev_connected" array does hold 2 values, but for some reason the for loop never reaches the 2nd one. Is there something I'm doing wrong? Thanks.
The result of getElementsByClassName is live, meaning that as you remove the class attribute it will also remove that element from the result. Using querySelectorAll is more widely supported and returns a static NodeList.
Also, you can more easily iterate the list using a for...in loop.
I would not recommend making an extra copy of the live list just to make it static, you should use a method that returns a static NodeList instead.
var prev_connected = document.querySelectorAll(".connected");
document.getElementById('demo').onclick = function() {
for(var i in Object.keys(prev_connected)) {
prev_connected[i].removeAttribute("class");
}
}
.connected {
background: rgb(150,200,250);
}
<div class="connected">Hello</div>
<div class="connected">Hello</div>
<div class="connected">Hello</div>
<div class="connected">Hello</div>
<div class="connected">Hello</div>
<button id="demo">Remove the classes!</button>
This is due to prev_connected being a live nodelist. When you update the element with that class it removes it from the nodelist which means the length of the nodelist reduces by one which means j is trying to find element 2 in an nodelist of length 1 which is why it doesn't work after the first iteration.
You can see this happening in the console in this demo.
One way you can fix this is by converting the nodelist to an array:
var prev_connected = [].slice.call(document.getElementsByClassName("connected"));
You should iterate in the opposite direction and use elem[i].classList.remove('name') for removing class name from each element Demo
document.getElementById("button").onclick = function () {
var prev_connected = document.getElementsByClassName("connected");
console.log(prev_connected);
for (var i = prev_connected.length - 1; i >= 0; i--) {
prev_connected[i].classList.remove("connected");
console.log(i, prev_connected[i - 1]);
}
}
There are another answers: https://stackoverflow.com/a/14409442/4365315

Combining getElementsByTagName and getElementsByClassName

I'm trying to combine getElementsByTagName and getElementsByClassName to narrow a search down and count the resulting nodes, but the second search always results in a length of 0, and I've no idea why.
<!DOCTYPE html>
<html>
<head></head>
<body>
<p>Stuff</p>
<p class="content">Stuff2</p>
<p>Stuff</p>
<p class="content">Stuff2</p>
<script type="text/javascript">
pElements = document.getElementsByTagName("p");
console.log(pElements);
for(i = 0; i < pElements.length; i++) {
console.log(pElements[i].getElementsByClassName("content").length);
}
//console.log(document.querySelectorAll('p.content').length);
</script>
</body>
</html>
I know I can use querySelectorAll for this like the line I have commented out, but I'd like to understand why the first solution isn't working, and what I can do to fix it.
Thanks!
The problem with the first example is that:
pElements[i].getElementsByClassName("content")
searches for children of the p element. But since it is actually on the same element, they are not found.
W3C reference:
"The getElementsByClassName() method returns a collection of an element's child elements with the specified class name"
EDIT: To find if a p element has the content class, instead of getElementsByClassName(), you could use
pElements[i].classList.contains("content")
which will return true if the element has the class. Reference
EDIT2: A more backwards-compatible way would be to get the className property, split it on spaces and iterate the array to see if the class is there.
var names = pElements[i].className.split(" ");
var found = false;
for(var i = 0; i < names.length; i++){
if(names[i] === "content"){
found = true;
break;
}
}
if(found){
//Your code here
}
You can NOT combine getElementsByTagName and getElementsByClassName. Because as mentioned by #juunas, pElements now consists of the result consisting of an array of all the <p> elements.
And when you apply the getElementsByClassName to this result-set, using pElements[i].getElementsByClassName("content"), it searches in the child elements of pElements.
Suggestive Result :
Use the getAttribute() function to check the class of each element in pElements, like,
pElements = document.getElementsByTagName("p");
console.log(pElements);
for(var i = 0, j = 0; i < pElements.length; i++) {
if (pElements[i].getAttribute("class") === "content") {
j++;
}
}
console.log("Length of the resulting nodes: ", j);
It's because your p-elements dont have any elements with the class "content". The p-elements itself have this class, so you cant find it and 0 is correct.
Change
<p class="content">Stuff2</p>
To
<p><span class="content">Stuff2</span></p>
And you will get 1 as the result.

GetElementByID - Multiple IDs

doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));
This doesn't work, so do I need a comma or semi-colon to make this work?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You have several different options:
You could implement your own function that takes multiple ids and returns multiple elements.
You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string .
You could put a common class names on all those nodes and use document.getElementsByClassName() with a single class name.
Examples of each option:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
or:
// put a common class on each object
doStuff(document.getElementsByClassName("circles"));
or:
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));
This will not work, getElementById will query only one element by time.
You can use document.querySelectorAll("#myCircle1, #myCircle2") for querying more then one element.
ES6 or newer
With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.
Example:
const elementsList = document.querySelectorAll("#myCircle1, #myCircle2");
const elementsArray = [...elementsList];
// Now you can use cool array prototypes
elementsArray.forEach(element => {
console.log(element);
});
How to query a list of IDs in ES6
Another easy way if you have an array of IDs is to use the language to build your query, example:
const ids = ['myCircle1', 'myCircle2', 'myCircle3'];
const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
No, it won't work.
document.getElementById() method accepts only one argument.
However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll() method:
document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");
I suggest using ES5 array methods:
["myCircle1","myCircle2","myCircle3","myCircle4"] // Array of IDs
.map(document.getElementById, document) // Array of elements
.forEach(doStuff);
Then doStuff will be called once for each element, and will receive 3 arguments: the element, the index of the element inside the array of elements, and the array of elements.
getElementByID is exactly that - get an element by id.
Maybe you want to give those elements a circle class and getElementsByClassName
document.getElementById() only takes one argument. You can give them a class name and use getElementsByClassName() .
Dunno if something like this works in js, in PHP and Python which i use quite often it is possible.
Maybe just use for loop like:
function doStuff(){
for(i=1; i<=4; i++){
var i = document.getElementById("myCiricle"+i);
}
}
Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.
<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>
<script>
document.getElementById('click').addEventListener('click', function(){
doStuff();
});
function doStuff() {
for(var i=1; i<=2; i++){
var el = document.getElementById("hello" + i);
el.style.display = 'none';
}
}
</script>
Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.
The best way to do it, is to define a function, and pass it a parameter of the ID's name that you want to grab from the DOM, then every time you want to grab an ID and store it inside an array, then you can call the function
<p id="testing">Demo test!</p>
function grabbingId(element){
var storeId = document.getElementById(element);
return storeId;
}
grabbingId("testing").syle.color = "red";
You can use something like this whit array and for loop.
<p id='fisrt'>??????</p>
<p id='second'>??????</p>
<p id='third'>??????</p>
<p id='forth'>??????</p>
<p id='fifth'>??????</p>
<button id="change" onclick="changeColor()">color red</button>
<script>
var ids = ['fisrt','second','third','forth','fifth'];
function changeColor() {
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).style.color='red';
}
}
</script>
For me worked flawles something like this
doStuff(
document.getElementById("myCircle1") ,
document.getElementById("myCircle2") ,
document.getElementById("myCircle3") ,
document.getElementById("myCircle4")
);
Use jQuery or similar to get access to the collection of elements in only one sentence. Of course, you need to put something like this in your html's "head" section:
<script type='text/javascript' src='url/to/my/jquery.1.xx.yy.js' ...>
So here is the magic:
.- First of all let's supose that you have some divs with IDs as you wrote, i.e.,
...some html...
<div id='MyCircle1'>some_inner_html_tags</div>
...more html...
<div id='MyCircle2'>more_html_tags_here</div>
...blabla...
<div id='MyCircleN'>more_and_more_tags_again</div>
...zzz...
.- With this 'spell' jQuery will return a collection of objects representing all div elements with IDs containing the entire string "myCircle" anywhere:
$("div[id*='myCircle']")
This is all! Note that you get rid of details like the numeric suffix, that you can manipulate all the divs in a single sentence, animate them... Voilá!
$("div[id*='myCircle']").addClass("myCircleDivClass").hide().fadeIn(1000);
Prove this in your browser's script console (press F12) right now!
As stated by jfriend00,
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes.
However, here's some example code I created which you can give one or a comma separated list of id's. It will give you one or many elements in an array. If there are any errors, it will return an array with an Error as the only entry.
function safelyGetElementsByIds(ids){
if(typeof ids !== 'string') return new Error('ids must be a comma seperated string of ids or a single id string');
ids = ids.split(",");
let elements = [];
for(let i=0, len = ids.length; i<len; i++){
const currId = ids[i];
const currElement = (document.getElementById(currId) || new Error(currId + ' is not an HTML Element'));
if(currElement instanceof Error) return [currElement];
elements.push(currElement);
};
return elements;
}
safelyGetElementsByIds('realId1'); //returns [<HTML Element>]
safelyGetElementsByIds('fakeId1'); //returns [Error : fakeId1 is not an HTML Element]
safelyGetElementsByIds('realId1', 'realId2', 'realId3'); //returns [<HTML Element>,<HTML Element>,<HTML Element>]
safelyGetElementsByIds('realId1', 'realId2', 'fakeId3'); //returns [Error : fakeId3 is not an HTML Element]
If, like me, you want to create an or-like construction, where either of the elements is available on the page, you could use querySelector. querySelector tries locating the first id in the list, and if it can't be found continues to the next until it finds an element.
The difference with querySelectorAll is that it only finds a single element, so looping is not necessary.
document.querySelector('#myCircle1, #myCircle2, #myCircle3, #myCircle4');
here is the solution
if (
document.getElementById('73536573').value != '' &&
document.getElementById('1081743273').value != '' &&
document.getElementById('357118391').value != '' &&
document.getElementById('1238321094').value != '' &&
document.getElementById('1118122010').value != ''
) {
code
}
You can do it with document.getElementByID Here is how.
function dostuff (var here) {
if(add statment here) {
document.getElementById('First ID'));
document.getElementById('Second ID'));
}
}
There you go! xD

Custom attribute issue

I'm trying to get the "quantity" attribute of multiple Elements ID at the same time.
Here's what I tried :
productMinimum : document.getElementsById("id1","id2").getAttribute("quantity")
How can I make this work? The "id1" and "id2" elements all have the "quantity" attribute.
Here's what it looks like from the HTML side :
<li class="product" name="RD-101" id="id1" price="18" quantity="2">
<li class="product" name="RD-101" id="id2" price="18" quantity="4">
The problem you're having is that getElementsById() doesn't exist (unless you've defined it elsewhere). What you should be using is getElementById(), albeit twice (as getElementById(), as its name implies, returns only one element, even if there are multiple elements with that same id, which is invalid mark-up, so please don't do that), and then pushing the returned elements into an array:
var products = [];
products.push(document.getElementById("id1"));
products.push(document.getElementById("id2"));
You could, of course, create your own function to return multiple elements based on their id:
function getElementsById(ids) {
if (!ids) {
return false;
}
else {
var elems = [];
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i])) {
elems.push(document.getElementById(ids[i]));
}
}
return elems;
}
}
console.log(getElementsById(['id1','id3']));​
JS Fiddle demo.
Bear in mind, though, that this returns a regular array, not a nodeList (as would be returned, for example, by getElementsByClassName()). And the returned array, even if it's only a single element, would have to be iterated over in the same way as any other array.
References:
getElementById().
nodeList.
push().
function getQuantity(id) {
return document.getElementById(id).getAttribute("quantity");
}
var quantId1 = getQuantity('id1');
var quantId2 = getQuantity('id2');
getElement*s*ById is returning an array. You need to get the individual items. If you had a whole lot of elements you could select by class product and write a simple function to loop over them and create an array.
There is no such function as getElementsById. you can use either getElementsByClassName or getElementsByName
https://developer.mozilla.org/en/DOM/document.getElementsByName
https://developer.mozilla.org/en/DOM/document.getElementsByClassName
Take note that getElementsByClassName is fairly new and not supported by older browsers.
Using pure JavaScript you need to write your own function for that:
function getQuantities() {
var args = Array.prototype.slice.call(arguments);
var quantityValue = 0;
for(var i = 0; i < args.length; i++) {
quantityValue += document.getElementsById(args[i]).getAttribute("quantity");
}
return quantityValue;
}
// your code
productMinimum : getQuantities("id1","id2")
As I understand it, document.getElementById takes one id at the time
Also, consider using html5 custom data attributes
There is no such thing as getElementsById()
But there is querySelectorAll, but it's not supported in IE7 and older though
here's a sample which should return the two <li> in a nodelist.
document.querySelectorAll('#id1, #id2')
You can only get one element at once (with getElementById()). If you want an array containing the quantities, use this:
[document.getElementById('id1').getAttribute('quantity'), document.getElementById('id2').getAttribute('quantity')]
Consider using jQuery, there you can use $('#id1, #id2') and besides that it supports easy access to data- attributes - what you are doing right now is invalid HTML since li does not have price or quantity attributes:
<li class="product" name="RD-101" id="id1" data-price="18" data-quantity="2">
<li class="product" name="RD-101" id="id2" data-price="18" data-quantity="4">
To get the quantities array:
$('#id1, #id2').map(function() { return $(this).data('quantity'); }).get();

Categories

Resources