admin管理员组

文章数量:1323342

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');

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');
Share Improve this question asked Oct 13, 2014 at 12:52 Umidjon UrunovUmidjon Urunov 6711 gold badge19 silver badges39 bronze badges 3
  • .html() gets the html, not the DOM elements, so you can't find the button by class etc. – devqon Commented Oct 13, 2014 at 12:54
  • Than how can I modify the content? – Umidjon Urunov Commented Oct 13, 2014 at 12:55
  • Either manipulate the DOM: $(this).parent().find(".button").attr("id", someValue) or use regex/replace to manipulate the html text. Depends on your use case – devqon Commented Oct 13, 2014 at 12:57
Add a ment  | 

4 Answers 4

Reset to default 3

.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
var modified_var = $(html_var).find('.button').attr('id');
var html_var = $(this).parent().html(); //Get HTML code
//Modify html_var
//...
$(this).parent().html(html_var); //Reapply modification 

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/r0huhx3v/8/

本文标签: javascriptJQuery assign HTML content to variableStack Overflow