Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Add ID instead of Class

Tags:

jquery

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?

like image 619
CLiown Avatar asked Feb 01 '10 13:02

CLiown


People also ask

How to add id in id in jQuery?

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

How to give id to element in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element.

What is addClass in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How do you give a Class ID in Javascript?

To add an id attribute to an element: Select the element using the document. querySelector() method. Use the setAttribute() method to add an id attribute to the element.


Video Answer


4 Answers

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

like image 200
Sarfraz Avatar answered Oct 24 '22 16:10

Sarfraz


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.

like image 41
Anthony Avatar answered Oct 24 '22 15:10

Anthony


$('selector').attr( 'id', 'yourId' );
like image 13
meouw Avatar answered Oct 24 '22 15:10

meouw


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,

like image 3
2 revs Avatar answered Oct 24 '22 14:10

2 revs