I have 7 elements with different margin-left and margin-top properties set on them through css styles on css file. I want to loop through them and collect these margins.
My jquery looks something like this now:
var $elements = $(".elements");
var elementsMargins = [];
$elements.each(function(index){
var elementObj = {
elIndex: index,
elMarginLeft: this.css("margin-left"),
elMarginTop: this.css("margin-top")
};
elementsMargins.push(elementObj);
});
However, I am not able to collect these values. Can someone advice or suggest anything to solve the issue?
Since css() is a jQuery method you have to wrap this in jQuery to use the method. Please use:
$(this).css("margin-left"), //and
$(this).css("margin-top")
instead of this.....
And, I would suggest using the map() method. You do not need to explicitly specify the index as it will be matching the index in the array of each object.
var elementsMargin = $('.elements').map(function() {
return {
elMarginLeft: $(this).css('margin-left');
elMarginTop: $(this).css('margin-top');
};
}).get();
Related
I need to pass some html code as a parameter, however, before I pass it, I need to change some src attribute values.
I cannot use lastIndexOf or any of those to modify the html value since I don't know which value the src's will have.
What I'm trying to do then, is to create an object containing the html, and then alter that object only. I don't want to alter the actual webpage.
is this possible??
What I did first was this:
$('[myImages]').each(function() {
var urlImg = "../tmpFiles/fileName" + counter;
$(this).attr('src', urlImg);
counter++;
});
So finally, I had the desired code like this:
myformData = { theChartCode: $('#TheDivContainingTheHTML').html() }
However, this actually changes the image sources on the webpage, which I don't want to.
Then I thought I could create a JQuery object with the html so I could alter that object only like this:
var $jQueryObject = $($.parseHTML($('#TheDivContainingTheHTML').html()));
But now, I can't figure out how to iterate within that object in order to change the src attribute's values of the desired images.
Any help will be really appreciated ;)
There are several ways to do It. First would be creating a clone of target element and use the same on the Fly. You can do like below:
var Elem = $('#TheDivContainingTheHTML').clone();
now do whatever you want like iterate, alter,insert,remove.
var allImages =$(Elem).children("img");
Thanks Much!
Depending on when you want to change the object, solution will be different. Let's pretend you want to change it after you click another element in the page. Your code will look like that :
var clonedHTML;
$('#clickable-element').click(function() {
var $originalHTML = $(this).find('.html-block');
var $cloneHTML = $originalHTML.clone();
$cloneHTML.find('.my-image').attr('src', 'newSrcValue');
clonedHTML = $cloneHTML.clone();
return false; //Prevents click to be propagated
});
//Now you can use `clonedHTML`
The key point here is the clone method : http://api.jquery.com/clone/.
You can clone the elements:
var outerHTML = $collection.clone().attr('src', function(index) {
return "../tmpFiles/fileName" + index;
}).wrapAll('<div/>').parent().html();
You can also use the map method:
var arr = $collection.map(function(i) {
return $(this).clone().attr('src', '...').prop('outerHTML');
}).get();
I'm currently making a game, and I'm trying to change the CSS values of a whole class of objects. For a single ID, I would use, document.getElementById("idHere"), but I need something like document.getElementByClass("classHere"). Thanks!
There is simply document.getElementsByClassName("myClass"), which returns an array of all the elements with that HTML class.
If you're using jQuery, you can do it with $(".myClass"), which will return a collection of all of the elements with that class.
There exists getElementsByClassName; see document.getElementsByClassName on MDN.
If you can use JQuery I suggest $('.classHere').
Two ways to do it:
document.getElementsByClassName("theClassName");
document.querySelectorAll(".theClassName");
These methods won't work on older browsers (like IE7 or IE8). In this case you'll have to iterate through elements to check the class name, or rely on a library like jQuery.
If you can't or don't want to use jQuery, do the following:
function changeClassName(className, newClassName) {
var elements = document.getElementsByClassName(className);
for (var i = 0; i < elements; ++i) {
var item = elements[i];
item.className = newClassName;
}
}
If you decide to use jQuery:
function changeClassName(className, newClassName) {
$('.'+className).toggleClass(newClassName);
}
If you need to change CSS values according to class name you can just use:
document.getElementsByClassName("classname");
this will return you an array of all elements in whole document that have class which you search.
This will allow you to write a loop to change CSS for all of returned elements.
My code:
http://codepen.io/vincentccw/pen/ecJDG
Basically what I want to get are all the data attribute values from the attr call data-designer
There are suppose to be 4 of them but I can only get the first one using:
var dsad = $('ul').attr("data-designer");
How do I fix this?
You can use each() to interact with each element individually:
$('ul').each(function(){
console.log($(this).data('designer'));
});
Or you can use map() to create an array of all the values which you can deal with separately:
var designers = $('ul').map(function() {
return $(this).data('designed');
});
console.log(designers);
Note, I used data to get the data-* attributes as this is quicker than accessing the attributes of the DOM element directly.
$('ul').each(function(){
console.log($(this).attr('data-designer'))
//you can add to an array also
});
You can use map() to project the attribute values into an array:
var designers = $("ul").map(function() {
return $(this).attr("data-designer");
}).get();
You need to use .each()
$('ul').each(function(){
console.log($(this).attr("data-designer"));
});
Codepen Demo
$('ul').attr("data-designer") just got the attribute for the first ul element. If to get all uls with "data-designer" attribute, try this:
$('ul[data-designer]').each(function(){
console.log($(this).attr("data-designer"));
});
I am new at JavaScript so I think my problem may be simple.
This works:
var convId = document.getElementById("wrapper");
convId.setAttribute("align","right");
But when I try to make it more specific:
var convId = document.getElementById("wrapper");
var convIdDl = convId.getElementsByTagName("dl");
convIdDl.setAttribute("align","right");
my definition list doesn't align to the right.
I have checked the HTML and CSS and everything is correct, but that shouldn't even matter
JavaScript overwrites them both.
The getElementsByTagName method returns a collection (to be more specific, a NodeList). You need to specify which element of that collection you want to use (just like you would when accessing an element in an array). Here I'm assuming you want the first:
convIdDl[0].setAttribute("align", "right");
As noted in the comments, you should definitely not be using the align attribute. CSS should be used in all cases.
The getElementsByTagName() function returns a collection of DOM elements, so you'll probably want to iterate through that and set the attribute on each element individually.
for(var i = 0; i < convIdDl.length; i++) {
convIdDl[i].setAttribute("align", "right");
}
I know this has been asked and answered a couple times already, but I'm still confused about how to reference the current object when iterating over a jQuery array. For example, the following code gives me the error TypeError: genH3Array[i].next is not a function. What is the right way to reference the current array object?
var genH3Array = $('#Generation_II').parent();
genH3Array.push($('#Generation_III').parent());;
genH3Array.push($('#Generation_IV').parent())
$.each(genH3Array, function(i, value)
{
if(genH3Array[i].next().attr("align") == "center")
{ genH3Array[i].next().next().next().insertBefore(heading.next())
}
genH3Array[i].next().next().insertBefore(heading.next())
genH3Array[i].next().insertBefore(heading.next())
})
EDIT: Thanks for all your help, everyone. I know this was probably a cinch for most of you, but it was a major headache for me. The corrected code is below:
var genH3Array = $('#Generation_II,#Generation_III,#Generation_IV').parent();
$.each(genH3Array, function(i, value)
{
console.log($(this).next());
if($(this).next().attr("align") == "center")
{
$(this).next().next().next().insertBefore(pokemonHeader.next())
}
$(this).next().next().insertBefore(pokemonHeader.next())
$(this).next().insertBefore(pokemonHeader.next())
$(this).insertBefore(pokemonHeader.next())
})
This part:
var genH3Array = $('#Generation_II').parent();
genH3Array.push($('#Generation_III').parent());
genH3Array.push($('#Generation_IV').parent());
...isn't really the way to use .push() against a jQuery object. When you .push() a value in, it should be a DOM element. Not a jQuery object.
You could simplify that entire bit like this:
var genH3Array = $('#Generation_II,#Generation_III,#Generation_IV').parent();
Now you'll have the .parent() of all three in the object.
Not entirely sure what the each is supposed to do, but it seems like you're trying to take the next three elements of each one, and insert them after some heading element.
$.each(genH3Array, function(i, value) {
if($(this).next().attr("align") == "center") {
heading.after( $(this).nextUntil('sometarget:last') );
}
heading.after( $(this).nextUntil('sometarget') );
});
I really don't know if this is what you want. It's a little hard to tell.
Both value and this point to the current item in the iteration, but that isn't your problem. Your problem is that the item returned by [] on a jQuery object isn't a jQuery object. You could do this:
$(genH3Array[i]).next()
Adding to what #patrick dw said: once you get the right selector, you can use the following syntax:
var getH3Array = ('#Generation_II,#Generation_III,#Generation_IV').parent().each(function() {
$(this); // this references the dom element matched, so:
if($(this).next().attr("align") == "center") {
// do something here
}
});
I think what you want is
var array = $("#c1, #c2, #c3").parent();
$.each(array, function(){
console.log($(this).next());
});
In $.each callback, the this variable point to the current element. If you are iterating through a jquery array like what you have, it will be iterating through the dom elements not jQuery objects, so you need to get the jQuery objects corresponding to them by using $(this).
jQuery.each