jQuery - Add ID instead of Class

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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...

Solution 2 - Jquery

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.

Solution 3 - Jquery

$('selector').attr( 'id', 'yourId' );

Solution 4 - Jquery

if you want to 'add to the id' rather than replace it

capture the current id first, then append your new id. especially useful for twitter bootstrap which uses input states on their forms.

    new_id = '{{old_id}} inputSuccess';
    old_id = that.attr('id');
    that.attr('id', new_id.replace( /{{old_id}}/ig,old_id));

if you do not - you will lose any properties you previous set.

hth,

Solution 5 - Jquery

Im doing this in coffeescript

booking_module_time_clock_convert_id = () ->
  if $('.booking_module_time_clock').length
    idnumber = 1
    for a in $('.booking_module_time_clock')
	  elementID = $(a).attr("id")
	  $(a).attr( 'id', "#{elementID}_#{idnumber}" )
	  idnumber++

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCLiownView Question on Stackoverflow
Solution 1 - JquerySarfrazView Answer on Stackoverflow
Solution 2 - JqueryAnthonyView Answer on Stackoverflow
Solution 3 - JquerymeouwView Answer on Stackoverflow
Solution 4 - JquerygeekbuntuView Answer on Stackoverflow
Solution 5 - JqueryNicolaiView Answer on Stackoverflow