tags:

views:

54

answers:

3

Hi. I'm trying to select all elements that have a class, get their ID's (if they have one), and append individual spans to the end of my document based on that information. This is as far as I've managed to get:

var element = $(".foo"),
    element_id = element.attr("id"),
    span_id = "for-" + element + "-id-" + element_id,   
    ;

I am hoping to append a span for each element gathered. Here are some examples of the span format I wish to achieve:

<span id="for-img-id-profile"></span>
<span id="for-div-id-content"></span>

If possible, I would also like to allow for elements without an ID to be formatted like so:

<span id="for-h1"></span>

I really appreciate the help as I'm very new to jQuery and am trying to learn.

A: 
rahul
A: 

I'm not entirely certain precisely what you'le hoping to accomplish, but you'll want something that looks more like this:

$('.foo').each(function()
{
    var $this = $(this);
    $('<span id="for-' + ($this.attr('id') || $this.get(0).tagName) +
       '"></span>').appendTo($(document));
});
Clint Tseng
Although this isn't working, it does seem to be the right direction Can you explain what this bit does (purely for education): ($this.attr('id') || $this.get(0).tagName)
criley
The || operator in this context essentially says that if the expression before it evaluates to null, return the expression after it instead. In this case, I'm checking if the element has an id; if it doesn't return the tagName instead. Doesn't match your example above exactly, but it should get you going in the right direction.
Clint Tseng
A: 

This works and is also fast, as it is better to insert all spans at once as one block.

//get .foo elements
var eles = $('.foo').toArray(), spans = [];
//create html-fragments for each found element
//respecting if no id is found
//no overhead in loop as no unneeded jQuery wrapping is used
for(var i=0; i < eles.length; i++) {
    var e = eles[i],
        tmp = '<span id="for-'+e.tagName.toLowerCase();
    if(e.id) {
        tmp += '-id-' + e.id;
    }
    tmp += '"/>';
    //collect html fragments in an array
    spans.push(tmp);
}
//join the html-fragments with "no-space" and insert after div#content
$("#content").after(spans.join(""));

Check http://jsbin.com/etafe for a demo

jitter
This works just as I needed it to. Thank you so much.
criley