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?
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')
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)
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With