javascript - jQuery scan through div class name, use those class names to print matching checkboxes -
i'm new javascript/jquery , wondering if @ possible collect div's class names , create checkboxes based on class names jquery. example.
<div class="champ"> <h3>reading</h3> </div> <div class="league1"> <h3>sheffield wednesday</h3> </div> <div class="prem"> <h3>sunderland</h3> </div> <div class="prem"> <h3>tottenham hotspur</h3> </div> <div class="champ"> <h3>watford</h3> </div>
say html file associated class names, result spit out checkboxes class names present divs while avoiding duplication of same class name.
so example above end looking like
- champ
- league1
- prem
any appreciated thanks.
i'd suggest:
// creating new elements: var newcheckbox = $('<input />', { 'type' : 'checkbox', 'name' : 'ukfootballclubs' }), newlabel = $('<label />'); wrapper = $('<div />').appendto('body'); // iterating on each div has class: $('div[class]').each(function(){ /* appending cloned label element, text set class-name of current div element: */ newlabel.clone().text(this.classname).appendto(wrapper); /* appending clone of new checkbox new label, allows click on label un/select checkbox: */ newcheckbox.clone().prependto(wrapper.find('label').last()); });
a altered version uses team-names (from div
) label
-text in order avoid having 2 check-boxes prem
text:
var newcheckbox = $('<input />', { 'type' : 'checkbox', 'name' : 'ukfootballclubs' }), newlabel = $('<label />'); wrapper = $('<div />').appendto('body'); $('div[class]').each(function(){ newlabel.clone().text($(this).text()).appendto(wrapper); newcheckbox.clone().prependto(wrapper.find('label').last()); });
however, if rather use class-names ('prem', 'champ', etc) can prevent duplicate checkbox-text checking existence of element contains text before appending new element text:
var newcheckbox = $('<input />', { 'type' : 'checkbox', 'name' : 'ukfootballclubs' }), newlabel = $('<label />'); wrapper = $('<div />').appendto('body'); $('div[class]').each(function(){ var text = $.trim(this.classname); if (!wrapper.find('label:contains('+text+')').length) { newlabel.clone().text(text).appendto(wrapper); newcheckbox.clone().prependto(wrapper.find('label').last()); } });
references:
Comments
Post a Comment