tags:

views:

107

answers:

3

I'm using the current jQuery:

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').addClass($(this).text());
        $('#container').addClass($(this).text());
        $('.stretch_footer').addClass($(this).text())
        $('#footer').addClass($(this).text());
    });
});

It applies the text held in the breadcrumb to 4 elements on the page, allowing me to style specifically to the page there on.

I'd like to try adding an ID instead of a class, how can I achieve this?

+1  A: 
$('selector').attr( 'id', 'yourId' );
meouw
+4  A: 

Try this:

 $('element').attr('id', 'value');

So it becomes;

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').attr('id', $(this).text());
        $('#container').attr('id', $(this).text());
        $('.stretch_footer').attr('id', $(this).text())
        $('#footer').attr('id', $(this).text());
    });
});

So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...

Sarfraz
How about caching? Rather than making 4 different jQuery objects of "this". var text = $(this).text();
PetersenDidIt
@petersendidt: agreed, i said in my answer, that he needs to modify as per needs.
Sarfraz
even better: `$('#nav, #container, .stretch_footer, #footer').attr('id', $(this).text());` .. not that using an ID here is a good idea.
nickf
This will only work once, after which the ID changes... also, you keep overriding the same IDs, so you might as well do it for `$('#nav, #container, .stretch_footer, #footer').attr('id', $('span .breadcrumb:first').text())` (or `last`, for `.stretch_footer`). Anyway, this is weird.
Kobi
+1  A: 

Keep in mind this overwrites any ID that the element already has:

 $(".element").attr("id","SomeID");

The reason why addClass exists is because an element can have multiple classes, so you wouldn't want to necessarily overwrite the classes already set. But with most attributes, there is only one value allowed at any given time.

Anthony