-1

I tried to add styling to a dynamically created element, and found this good working solution here on the site.

-----EDIT: adding more code -----

function createAndShowPatch(){
  selected = $('.active');
  var radiosForPatch = [];
  for (radio in selected){
  //must be a beeter way to iterate over "selected"
  //without checking if Object and has property "id"... any suggestions? 
    if (typeof selected[radio] === "object" && "id" in selected[radio]){
        radiosForPatch.push(($.grep(radios, function(e){ return e.id == selected[radio].id; }))[0]);
      }
  }


  var patch = new Patch(radiosForPatch);
  var guiPatch = createNewGUIPatch(patch);
  var style = {
    position: "absolute",
    top: mouseY +"px",
    left: mouseX +"px"
  }

  $(guiPatch).appendTo($(".container")).css(style).draggable();
}

function createNewGUIPatch(patch){
  var patchToReturn;
  var patchContent = "";
  for (radio in patch.radios){
    patchContent += "<p> " + patch.radios[radio].name + "</p>";
  }

  patchToReturn = "<div class='patch'><h1>Patch</h1>" + patchContent + "</div>";
  return patchToReturn;
}

-------End of edit ------ But that made me wonder why what I tried didn't work and think maybe I am missing some basic important thing related to JQuery (or even javascript :-/ )

so , the question is, what is the difference between this:

$(guiPatch).appendTo($(".container")).css(style);

and this (splitting to 2 lines):

$(guiPatch).appendTo($(".container"));
$(guiPatch).css(style);

and why the first one is working while the second one didn't.

Thanks :).

3
  • what is style value? Commented Jul 12, 2015 at 6:43
  • 1
    Hint: assuming guiPatch is a piece of HTML markup, each call to $(guiPatch) creates new DOM elements. $(guiPatch)[0] !== $(guiPatch)[0]. Commented Jul 12, 2015 at 6:46
  • @DCoder - that must be it :). if you want - put it as an answer and I will mark it as chosen one. Commented Jul 12, 2015 at 6:59

1 Answer 1

1

Lets say, guiPatch contains some HTML e.g. <div>ABC</div> Now your 1st code will then look like,

$('<div>ABC</div>').appendTo($(".container")).css("color","yellow")

jQuery functions can be chained together because in each stage it returns the object and hence the next functions gets to work on the returned object. So, $('<div>ABC</div>') is returning <div>ABC</div> object to appendTo functions. Again, $('<div>ABC</div>').appendTo($(".container")) is also doing its work on that object and returning/passing the same object to the next function, i.e. .css()

Now when you are breaking it in 2 lines,

$('<div>ABC</div>').appendTo($(".container"));
$('<div>ABC</div>').css("color","yellow");

The 1st line is appending a <div>ABC</div> object to .container. fine. But the 2nd line is also creating another <div>ABC</div> object and passing it to .css() function, which is doing its job i.e. applying the style and returning an object <div style="color: yellow;">ABC</div>. But we are unable to see the change because we are not appending/adding this new <div>ABC</div> to anywhere in the DOM. This object is lost as soon as .css() function finishes its job.

Hope it is clear now.

Try it in Chrome Developer Tools. copy and paste and press enter every piece/step of code that I have broken down and you will be able to see it in action.

Thank you.

EDIT / ADDITION: ***** Additional Note for your comment inside code ************

Whatever jQuery($) returns is always and object. So, checking if it is an object is redundant [imo]. You can check it by typing these codes in Chrome Dev Console,

typeof($(''))   // returns object, though empty

and also in the console of any webpage type the following,

typeof($('div'))   // also an object, but an array of all the divs in that webpage

you can also use .each directly, instead of another for loop, if u prefer,

$('.active').each(function(index){
  $(this) //$(this) will give you an object to work on in each iteration 
})

Please comment if you find any exception to this, I will update my answer.

Sign up to request clarification or add additional context in comments.

5 Comments

as clear as it gets :) can you refer to my comment as well (//must be a better way to iterate over "selected" //without checking if Object and has property "id"... any suggestions?) Thanks you.
Edited the post. IMO the typeof selected[radio] === "object" check is redundant, because, even if $('.active') returns an array of objects, each element in that array is bound to be an object. Please test and let me know if you found otherwise. Thank you and Welcome :) @JimmyBoy
Replace for loop with .each and thus you can omit the array access operator selected[radio] and directly use the object using $(this) inside your loop :) Play with it and jQuery is really fun @JimmyBoy
you are probably right about JQuery always returning an object, but what i am checking is not the returned value from JQuery but the returned value in a specific position (selected [radio] ) and that not always an object :) I will now try the .each thing, Thanks man.
Try to think it this way. Instead of "radio", name it "i" in your for loop, because for(var i in array) is same as for(var i=0; i<array.length; i++). or try Console.log(radio) in each iteration. So, "selected" which is returned by jQuery is an "Array of Objects", like, [object, object, object]. Therefore, selected[radio] (selected[i]) should be an object. This is what I was trying to tell. Anyway, always welcome @JimmyBoy . It is always fun to discover new things by doing :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.