开发者

Jquery – Append selected items in spans

开发者 https://www.devze.com 2022-12-26 05:38 出处:网络
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. T开发者_开发百科his is as far

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. T开发者_开发百科his 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.


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


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));
});


Something like

$(".foo").each(function(index){
    var id = "";
    if($(this).attr("id") !== "")
    {
        id = "for-" + $(this).attr("id"); 
    }
    else
    {
       id = "for-h" + index;
    }

    $("<span />").attr("id", id).after("#content");
});

Note

You will have to be sure that ids should be unique in the document, and no two elements have the same id.

0

精彩评论

暂无评论...
验证码 换一张
取 消