Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting HTML into DIV using JQuery

Tags:

html

jquery

I've got a bunch of buttons nested within div tags in my html

<div class="button-wrapper">
    <button class="button-class">Click here</button>
</div>
<div class="button-wrapper">
    <button class="button-class">Click here</button>
</div>
...

Clicking on the button posts some data using JQuery and returns some HTML through a .ajax success function. I'm trying to replace the content of the div for each button that is clicked, but for some reason my JQuery selector doesn't seem to be working.

I'm trying the following within my success function:

$(this).parent().html(data);

I know that the data is being posted successfully and that the success function is working. What's weird is that the following works:

$(".button-wrapper").html(data);

but obviously this adds the HTML to every div, not just the one for the button that is clicked.

Does anyone know where I might be going wrong here?

like image 268
rolling stone Avatar asked Jul 08 '11 00:07

rolling stone


People also ask

How do I put HTML in a div?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

How do I get HTML using jQuery?

To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.

How HTML elements are used in jQuery with example?

What is the use of html() method in jQuery ? The html() method in jQuery is used to get the contents of the first element in the set of matched elements or is used to set the HTML contents of every matched element. It returns the content of the first matched element. This function does not accept any arguments.


1 Answers

In jQuery 'this' is commonly overwritten within a callback. The workaround is to reference this using another variable:

var _this = this; //or var $_this = this;
$(_this).parent().html(data);
like image 150
Justin Lucas Avatar answered Oct 16 '22 07:10

Justin Lucas