Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can jQuery get an attribute from an HTML tag in a string variable

Inside JavaScript, At runtime I am getting HTML code for checkbox inside a string as follows:

var chk="<input type='checkbox' id='checkbox1' name='chk1' />";

I want to get the ID of the checkbox.

My Question is:

Does jquery support any api to to retrive value of id?
Or
Do I have to follow the JavaScript api to achieve the same?

Note: Currently I am using following JavaScript code:

var i=chk.indexOf("id");
var s=chk.substring((i+4));
var j=s.indexOf("'");
s=s.substring(0,j);

Finally s contains id of checkbox.

like image 930
Prasad Jadhav Avatar asked Dec 06 '25 20:12

Prasad Jadhav


2 Answers

Try this,

Live Demo

var chk = $("<input type='checkbox' id='checkbox1' name='chk1' />");

alert(chk.attr('id'));​
like image 157
Adil Avatar answered Dec 08 '25 10:12

Adil


Yes, you can do it easily with jquery, as follows:

var chk="<input type='checkbox' id='checkbox1' name='chk1' />";
id = $(chk).attr('id');
alert(id); //alerts 'checkbox1'

See working demo

like image 35
Nelson Avatar answered Dec 08 '25 08:12

Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!