My script needs to dynamically create a stylesheet in the section of the page (rather than put inline styles on each element, because I need to override these styles with media queries later on).
The Code
for (var i=0; i<theElements.length; i++){
$(theElements[i]).not('.responsive-wrap').each(function(i, elem){
var theWidth = $(this).width();
var parentWidth = $(this).parent().width();
$(this).addClass('element' + [i]);
$("#dynamicStylesheet").text('.element' + [i] + ' {max-width: ' + theWidth + 'px;}');
});
}
The main question is:
This completely overrides the text in the #dynamicStylesheet each run of the loop (so when I load the page there is only one rule for .element22). How can I make it ADD the text without overwriting?
Sub-questions for bonus points:
-
This works for the most-part, but ONLY when
[i]is in square
brackets. Why is this?Do I need the
for loophere, or is.each(function(){})essentially
creating afor loopanyway? There’s anothereachfunction below this one inside thefor loopthat I haven’t posted to keep it succinct.
Okay, so, a few things. Assuming that
theElementsis an array of HTML elements, theeachis unnecessary. But that doesn’t seem to be the case, since you sayelement22is showing up (your code as its written would only createelement0over and over again iftheElementswas an array of HTML elements). So apparentlytheElementsis an array of arrays, or an array of jQuery objects. Which is weird given its name, but let’s power through.As others have mentioned, you’re overwriting the text every iteration, which is bad. Building a string is slightly better, but you’re still doing repeated string concatenation, which is slow. If we had to do this, we should append to an array and then join it together at the end (which is faster, since appending to a string creates the entire string from scratch every time).
Now, that works, and will do what you want. But this is almost definitely not the right way to do whatever it is you’re trying to do. Dynamically building CSS on the client is not good, unless you’re writing something like a CSS editor. There are much easier ways to solve whatever problem led you down this path.
If creating a client-side stylesheet is absolutely vital, then there are better ways to do this, too. Create a single CSS rule that applies to all the elements of the elements of
theElements(wow, look at that sentence). That’s not possible if they’re chosen randomly, but if you arrived at them through some logical query you can use the same one in CSS.As far as the
[i]thing goes — I don’t know what to tell you. Due to the weird way JavaScript stringifies arrays, they’re equivalent, and ifidoesn’t work for you then there’s something very wrong. I would be usingi.toString()if I were you, butishould work fine.Edit
If
theElementsis an array of tag names, this can be simplified to: