Mdb
Mdb

Reputation: 8568

Convert string into jQuery object and add attribute

I have the following HTML:

<label>Lobby Template:</label>

I want to convert it to jquery object and add an attribute id with a value of test:

<label id="test">Lobby Template:</label>

Upvotes: 0

Views: 1318

Answers (6)

Ranjith Ramachandra
Ranjith Ramachandra

Reputation: 10764

labels = $('label')
$.each(labels, function(i, label){
    if($(label).html() == 'Lobby Template:' ){
    $(label).attr("id", "test")
    }
})

Upvotes: 0

dfsq
dfsq

Reputation: 193261

I like this syntax:

var $el = $("<label>", {
    id: "test",
    text: "Lobby Template:"
});

Upvotes: 2

Mihai Matei
Mihai Matei

Reputation: 24276

You can do it like this

$('label').attr('id','test');

Upvotes: 0

user1726343
user1726343

Reputation:

$('label')[0].id="test";

You need to have some sort of hook to identify your element. http://jsfiddle.net/RQ3vH/1/ is a demo.

Upvotes: 0

Buzz
Buzz

Reputation: 6320

use jquery attr

$('label').attr('id', 'test');

Upvotes: 0

lrsjng
lrsjng

Reputation: 2615

var $el = $('<label>Lobby Template:</label>').attr('id', 'test');

Upvotes: 3

Related Questions