RANDOM JQUERY SNIPPETS


/ Published in: jQuery
Save to your folder(s)

Useful random jQuery snippets.


Copy this code and paste it in your HTML
  1. //Remove a word with jQuery
  2. var el = $('#id');
  3. el.html(el.html().replace(/word/ig, ""));
  4.  
  5. //jQuery timer callback functions
  6. window.setTimeout(function() {
  7. $('#id').empty();
  8. }, 1000);
  9.  
  10. //Verify that an element exists in jQuery
  11. if ($('#id').length) {
  12. // do stuff
  13. }
  14.  
  15. //Dynamically adding <div> elements with jQuery
  16. $('<div>hello<\/div>').appendTo(document.body);
  17.  
  18. //Searching for Text with jQuery
  19. //This function performs a recursive search for nodes that contain a pattern. Arguments are //a jQuery object and a pattern. The pattern can be a string or a regular expression.
  20. $.fn.egrep = function(pat) {
  21. var out = [];
  22. var textNodes = function(n) {
  23. if (n.nodeType == Node.TEXT_NODE) {
  24. var t = typeof pat == 'string' ?
  25. n.nodeValue.indexOf(pat) != -1 :
  26. pat.test(n.nodeValue);
  27. if (t) {
  28. out.push(n.parentNode);
  29. }
  30. }
  31. else {
  32. $.each(n.childNodes, function(a, b) {
  33. textNodes(b);
  34. });
  35. }
  36. };
  37. this.each(function() {
  38. textNodes(this);
  39. });
  40. return out;
  41. };
  42.  
  43. //Case-Insensitive Contains Check
  44. //By using case-insensitive regular expressions, this becomes rather easy:
  45. var pattern = /exp/i;
  46. $('#id').filter(function() {
  47. return pattern.test($(this).text());
  48. });
  49.  
  50. //Reload an IFrame
  51. //Accessing the contentWindow property to obtain the location object.
  52. $('#iframe').each(function() {
  53. this.contentWindow.location.reload(true);
  54. });
  55.  
  56. //Callback for IFrame Loading
  57. //With the onload event, your code is called when an IFrame has finished loading.
  58. $('#iframe').load(function() {
  59. // do something
  60. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.