I'm trying to write this:
$('.circle_div').each(function(){
var $this = $(this),
thisWidth = $this.width();
$this.css('height', thisWidth + 'px');
});
in javascript like this:
var circle_div = document.getElementsByClassName('circle_div');
for (el in circle_div){
var thisWidth = el.style.width;
el.style.height = thisWidth + "px";
}
I also tried for...of and for each, and a regular for loop incrementing var i. The jquery function works but the javascript doesn't. Any idea what I'm doing wrong?
Eeeck. Never use for/in to iterate elements of an array or array-like object (doing so will include other iterable properties in addition to just the array elements).
Plus el in your loop is the index, not the value. You have to use circle_div[index] to get the element from the nodeList. But, you MUST switch to a traditional for loop, not for/in.
var circle_div = document.getElementsByClassName('circle_div');
for (var i = 0; i < circle_div.length; i++) {
var item = circle_div[i];
item.style.height = item.style.width;
}
You also have to remove the + "px" because the units are already there in plain javascript.
For more details on using for loop with document.getElementsByClassName() (including ES6 info), see this other answer: For loop for HTMLCollection elements.
If you convert the NodeList object that returns getElementsByCLassName to a regular array, you can use the Array.prototype.forEach method on it:
// Get the divs, and convert the NodeList to a regular array.
var circle_div = [].slice.call(document.getElementsByClassName('circle_div'), 0);
circle_div.forEach(function (el) {
el.style.height = el.clientWidth + "px";
});
This way looks more similar to your jquery code.
Check the fiddle: http://jsfiddle.net/7ew39phu/
Edit: I realize I should have used clientWidth, instead of style.width. The reason is that style properties seem to be only available if they were set using JavaScript, not if they were set using an css sylesheet.
Anyway, I fixed the code.
var circle_div = document.getElementsByClassName('circle_div');
for (var i=0,l=circle_div.length; i<l; i++){
circle_div[i].style.height = circle_div[i].style.width;
}
Related
I have here some code, in which I am trying to change all of something on a page.
var allElements = document.getElementsByTagName('*');
var tag = '.style.backgroundColor';
var val = 'black';
for (var i = 0; i < allElements.length;i++) {
allElements[i] + tag = val;
}
How can I make this work?
This can be done, but not the way you are doing it. You'll need to pass (as an index, using bracket notation) the CSS property name (a string) into the object returned by accessing the .style property.
Also, don't use .getElementsByTagName() as it's a 25+ year old API that returns a "live" node list, which can hurt performance. Instead, use .querySelectorAll() and loop over the returned collection with the Array.forEach() method, which is an alternative to a traditional for counting loop that is a bit easier to work with since you don't have to manage any loop counters and get direct access to the element you are iterating.
var allElements = document.querySelectorAll('*');
var tag = 'backgroundColor'; // Just store the name of the CSS property
var val = 'black';
// Use the more modern Array.forEach() method of looping
allElements.forEach(function(element){
element.style[tag] = val; // Pass the style object's property name as an index
});
* { color:white; border:2px solid white; }
<div>This is a div<br>that spans two lines.<div>
<p>Here's a paragraph</p>
<h1>And a Heading 1</h1>
I have a for loop in my jquery script
var images[];
for(i=0;i<$('#imageHolder div').length;i++)
{
images.push($('#imageHolder div:eq( i )').attr('alt'));
console.log($('#imageHolder div:eq(i )').attr('alt'));
}
I am not able to add the elements to the array and the console.log says undefined in the console.
What is my possible error and how that can be corrected?
jQuery has useful method for this task, called $.fn.map:
var images = $('#imageHolder div').map(function() {
return $(this).attr('alt');
}).get();
Will produce an array of images alt attributes.
You have a typo:
images.push($('#imageHolder div:eq(' + i + ')').attr('alt'));
you need to concat i ^^^^
By the way, don't select your element every time in the for
var divs = $('#imageHolder div');
for(i=0; i < divs.length; i++)
i is a variable so need to use concatenation
$('#imageHolder div:eq('+ i + ')').attr('alt')
A more efficient way is to use .map(), in your case you are evaluating the selector many times which is not a optimal way
var images = $('#imageHolder div').map(function () {
return $(this).attr('alt')
}).get()
footLinks is an array of selected DOM elements via jquery. Here's the code im working on:
var footLinks = $('.links li');
for (var i = 0; i < footLinks.length; i++) {
var footLink = footLinks[i];
var footLinkWidth = footLink.width();
console.log('Width: ' + footLinkWidth);
}
How do I get each element's width?
I think it would be better if you wrote it like this:
$('.links li').each(function(d) {
console.log("Width: "+$(this).width())
});
jQuery returns object in array, and when you want to use each DOM element in loop that is work with JavaScript function, but width() is not native function, if you want to get width using jQuery width() method then create jquery object like $(footLink) so you can also use offsetWidth native method
$(footLink).width();
OR
footLink.offsetWidth;
Use jQuery wrapper for the footLink:
var footLinks = $('.links li');
for (var i = 0; i < footLinks.length; i++) {
var footLink = footLinks[i];
var footLinkWidth = $(footLink).width();
console.log('Width: ' + footLinkWidth);
}
I am trying to get all the form elements within a specific div, and combine them into a single array using the array concat() method:
var div_id = 'some_div_id'; // in real life this is passed as a function parameter
var child_inputs = document.getElementById(div_id).getElementsByTagName('input');
var child_textareas = document.getElementById(div_id).getElementsByTagName('textarea');
var child_selects = document.getElementById(div_id).getElementsByTagName('select');
var field_elements = child_inputs.concat(child_textareas, child_selects); // this doesnt work?
However the script fails at the last line I'm not sure why. I can't use .childNodes because the div_id being passed is not the direct parent.
getElementsByTagName returns a NodeList not an array, so you can't use concat.
If you want to "transform" the nodeList into an array you could call slice from the Array protype chain:
var div_id = 'some_div_id',
divIdElement = document.getElementById(div_id); //cache the element
var getArrayFromTag = function(tagname) {
//get the NodeList and transform it into an array
return Array.prototype.slice.call(divIdElement.getElementsByTagName(tagname));
}
//Get the arrays
var child_inputs = getArrayFromTag('input');
var child_textareas = getArrayFromTag ('textarea');
var child_selects = getArrayFromTag ('select');
//use concat
var field_elements = child_inputs.concat(child_textareas, child_selects);
Those methods don't return an Array. Instead it's a NodeList or perhaps an HTMLCollection. (See the note under Syntax.)
You might loop over each nodelist and form an array of them 'by hand'.
I am trying to store an array of objects in an array by going through each paragraph element in a div container with the .get() method. I try to access the attribute with .attr() but it doesn't seem to work. How would I modify this code in order to be able to access the 'id' attribute of each message?
var messages = $("#message_container p").get();
var idstest = [];
for (int i = 0; i < messages.length; i++){
idstest.push(messages[i].attr("id"));
}
I think it has to do with some fundamental incompatibility with .get() and .attr(). When I 'alert' the objects provided by .get() I get [object HTML---]. I'm assuming that is not the form necessary in order to use .attr?
get will give you the DOM element. These are NOT jquery objects so you can't use attr on them. There's no reason to use get at all here.
var messages = $("#message_container p");
var idstest = [];
messages.each(function(){
idstest.push($(this).attr("id"));
});
http://jsfiddle.net/ujdeH/
EDIT: You also can't use int.
If for some reason you did want to use get to get the raw DOM elements, you would then just use .id:
http://jsfiddle.net/ujdeH/1/
var messages = $("#message_container p").get();
var idstest = [];
for (var i = 0; i < messages.length; i++) {
idstest.push(messages[i].id);
}
try instead:
var idstest = [];
$("#message_container p").each(function(i){
idstest.push($(this).attr("id"));
});
Just wanted to add the $.map shortcut: http://jsfiddle.net/UuWq3/.
var idstest = $.map(messages, function(elem) {
return $(elem).attr("id");
});
$.map returns a new array based on the original array (or jQuery object). The array returned is constructed with the function you pass (in this case, messages is transformed by the function such that each element is replaced with it's ID).
You should wrap the object in jQuery container:
$(messages[i]).attr("id")
Actually no need for jQuery here, this pure JavaScript will work just fine on all browsers:
var idstest = [];
var container = document.getElementById("message_container");
if (container) {
var messages = container.getElementsByTagName("p");
for (var i = 0; i < messages.length; i++) {
idstest.push(messages[i].id);
}
}
jQuery is all good and powerful, but if you can achieve the same task with short/easy enough pure JS then why not?
This said, if all your existing code is jQuery then you might be better off sticking with it (using the code from other correct answers here) just for sake of consistency and readability.