Umidjon Urunov
Umidjon Urunov

Reputation: 671

JQuery assign HTML content to variable

I am trying to get HTML code to jquery variable and it is working in following code:

var html_var = $(this).parent().html();

But when I want to modify "html_var" I cannot do it, I mean, the html code contains button tag and I need to change this button's value and id? I tried with "find" but I don't why it didn'y work.

var modified_var = html_var.find('.button').attr('id');

Upvotes: 2

Views: 6371

Answers (4)

Leggy
Leggy

Reputation: 682

As others have said, do not use the .html() in the html_var.

var html_var = $(this).parent();

Since it is a button tag you do not use the period/fullstop (.) Instead do this:

var modified_var = html_var.find('button'); 

Notice there is no (.) in the find?

To change the id do this:

modified_var.attr("id","new_id_goes_here");

To change the value of the button do this:

modified_var.html("value of button here");

To find out what the id is you can do this:

var theid = modified_var.attr("id");

EDIT:

Check out my fiddle: http://jsfiddle.net/r0huhx3v/8/

Upvotes: 1

robobot3000
robobot3000

Reputation: 589

.html() returns the html as plain text, so you can either operate on the parent object:

var $parent = $(this).parent();
$parent.find.('.button').attr('id', newValue);

or you can operate on the text

var html_var = $(this).parent().html();
//modify the text
$(this).parent().html(html_var); //replace the parent html with the modified html

Upvotes: 3

alquist42
alquist42

Reputation: 749

var modified_var = $(html_var).find('.button').attr('id');

Upvotes: 2

blue112
blue112

Reputation: 56462

var html_var = $(this).parent().html(); //Get HTML code
//Modify html_var
//...
$(this).parent().html(html_var); //Reapply modification 

Upvotes: 1

Related Questions