MOCKSTACKS
EN
Questions And Answers

More Tutorials









Jquery Other API Methods


jQuery offers a variety of methods that can be used for DOM manipulation.

The first is the .empty() method.

Imagine the following markup:

<div id="content">
 <div>Some text</div>
</div>

By calling $('#content').empty();, the inner div would be removed. This could also be achieved by using $('#content').html('');.
Another handy function is the .closest() function:

<tr id="row_1">
 <td><button type="button" class="delete">Delete</button>
</tr>

If you wanted to find the closest row to a button that was clicked within one of the row cells then you could do this:

$('.delete').click(function() {
 $(this).closest('tr');
});

Since there will probably be multiple rows, each with their own delete buttons, we use $(this) within the .click() function to limit the scope to the button we actually clicked.

If you wanted to get the id of the row containing the Delete button that you clicked, you could so something like this:

$('.delete').click(function() {
 var $row = $(this).closest('tr');
 var id = $row.attr('id');
});

It is usually considered good practise to prefix variables containing jQuery objects with a $ (dollar sign) to make it clear what the variable is.

An alternative to .closest() is the .parents() method:

$('.delete').click(function() {
 var $row = $(this).parents('tr');
 var id = $row.attr('id');
});

and there is also a .parent() function as well:

$('.delete').click(function() {
 var $row = $(this).parent().parent();
 var id = $row.attr('id');
});

.parent() only goes up one level of the DOM tree so it is quite inflexible, if you were to change the delete button to be contained within a span for example, then the jQuery selector would be broken.

Conclusion

In this page (written and validated by ) you learned about Jquery Other API Methods . What's Next? If you are interested in completing Jquery tutorial, your next topic will be learning about: Jquery DOM Traversing.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.