I am trying to use the following jQuery code to add a div with class col_box inside the col_left div:
$('#col_left').add('div').addClass('col_box');
My DOM tree looks like this:
<div id="header">Header</div>
<div class="col_container">
<div id="col_left">
<div class="col_box">A</div>
<div class="col_box">B</div>
</div>
</div>
However the jQuery code isn’t working. It adds the class col_box to every element on the page.
.add()adds a selector to the selection, it doesn’t create or add elements.$('#col_left')means *select element id col_left*.add('div')means add all divs of the page the the selectionSo at this point you’ve selected #col_left and all the divs.
.addClass('col_box')means *add the class col_box to all elements of the selection*.Here is how to create a div and add it to #col_left:
Or: