Creating list of divs by class

I'm not sure whether I should be doing this with jquery or php, but I have a html page with several divs of the same class, but different ids. ie:

<div class="something" id="furniture">contents</div>
<div class="something" id="lighting">contents</div>
<div class="something" id="homewares">contents</div>

What I'm looking at doing is creating a <ul> generated by the ids of any div with the class "something".

Would I be best doing this using jquery? and how would I best go about creating a list/menu of these divs?


well, to "convert" that structure into ul's, code should look like:

 var $target = $('.something'),
     $parent = $target.parent(),
     $list   = $('<ul/>', {
       id:     'your_id_here',
       css:    {
           backgroundColor:  'red'
           // more css attributes, or use class: to assign a css class

     $list.append('<li>' + $(this)[0].id + '</li>');


That would replace the divs with ul's. Importan thing in this example is to remove the original div because of the ids, which have to be unique in a valid html markup.

You would use PHP if that is an option (i.e. you know the ids when you load the page and are generating them from your PHP already), otherwise only the people with JavaScript enabled are going to see your page content (and search engines would probably punish this "hidden" content).

If you have the list of ids in a PHP array you would do something like this:

    $ids = array('furniture, 'lighting', 'homewares');
  <?php foreach ($ids as $id) : ?>
  <?php endforeach; ?>

If you wanted to use jQuery you could do this:

$('body').append('<ul id="yourID"></ul>');

$('div.something').each(function() {
    $('ul#yourID').append('<li>' + $(this).id + '</li>');

Update (you want to replace the div tags and put the ids on the li tags)

$('body').append('<ul id="yourID"></ul>');

$('div.something').each(function() {
    var $id = $(this).id;
    $('ul#yourID').append('<li id="' + $id  + '">' + $id  + '</li>');

Assuming the HTML you've provided is rendered, and that you have an available UL element on the page, you can use JQuery to do (something like) the following

function(index, Element) { 
    var newListElement = jQuery(document.createElement('li'));

It's a bit unclear as to the restrictions that are imposed upon you, but I hope this helps.

Need Your Help

Angular Js: Factory, Service and Providers. When to use which?

javascript angularjs factory angular-services angular-providers

I found that there are many answers online and here in stack overflow. But, none clarifies as to which one to use in which scenario as all three can perform the same set of functions?