Gleb Oleg Gleb Oleg - 1 year ago 86
Javascript Question

jQuery multiple selection does not work

I have a divs that get created with an id, and I add span with preset CSS properties

$(".main").append("<div class=largeBox id=" + counter + "</div>");
$(".largeBox").append("<span class=mainTitle></span>");

Then I am trying to load text into boxes, but selection could not work. Can anyone advise me why?

var id = "#" + counter;
$(id + " .mainTitle").text(title);

Answer Source

You don't actually need to have quotes around classnames or IDs and I purposely omitted them in my answer to show that's not the problem here.
Your had a problem that you were actually appending all the spans to all the previous largebox divs. I added a for loop so you can see how it works now but the use of $(".largeBox").eq(counter) makes the titles append to each div separately.

Also, IDs shouldn't start with a number (if you want to support HTML4 browsers), so now their form is lb-number (lb for largeBox)

var counter = 0;
$(".main").append("<div class=largeBox id=lb-" + counter + "></div>");
$(".largeBox").eq(counter).append("<span class='mainTitle'></span>");
var id = "#lb-" + counter;
$(id + " .mainTitle").text("test");
<script src=""></script>
<div class="main">


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download