-4

I'm trying to remove a jQuery dependency and replacing this .each with a loop is proving tricky.

// inline <img> when src = .svg so it is styled with CSS 

$('[src$=".svg"]').each(function() { // get .svg 
  var $img = $(this);
  var imgURL = $img.attr("src"); // get src url
  $.get(
    imgURL,
    function(data) { // Get the SVG guts from image file
      var $svg = $(data).find("svg");
      $img.replaceWith($svg);  // Replace img with SVG guts
    }, "xml"
  );
});
AndyFitz
  • 11
  • 4
  • What is your question? What have you tried already that isn't working? – jmargolisvt Oct 02 '18 at 02:17
  • Depending on what you want, you can use either `map()` or `forEach()`. But replacing the `.each()` call isn't the only jQuery dependency. You also need to implement the matching with something else. – Code-Apprentice Oct 02 '18 at 02:22
  • http://youmightnotneedjquery.com/ <- everything you need, right there. Come back and ask questions if you have an actual issue – Phil Oct 02 '18 at 02:25
  • Welcome to stackoverflow @AndyFitz, as such, you question is complicated to understand since it is difficult to see what your are asking. Can you please put some more details ? (error message, what blocks you) – Nathan Ripert Oct 02 '18 at 02:28
  • My current code snippet above is the last piece I use that has a dependency on JQuery, I'm just trying to remove that dependency. I'm trying this right now: `var svgs = $('[src$=".svg"]'); for(var i = 0; i < svgs.length; i++){ }` – AndyFitz Oct 02 '18 at 02:46
  • 1
    Can you please clarify what you mean by “proving tricky”? – vol7ron Oct 02 '18 at 02:56
  • https://codepen.io/andyfitz/pen/YObMdE?editors=0110 - existing working code with testing code commented out – AndyFitz Oct 02 '18 at 02:56

1 Answers1

1

Browsers implement jQuery-style selectors and collection methods. So a jQuery each loop can be be emulated in vanilla JavaScript using document.querySelectorAll to return a NodeList, which is an array-like object that's kinda sorta like a jQuery collection:

const nodeList = document.querySelectorAll('[src$=".svg"]')

You can borrow the forEach method from arrays:

Array.prototype.forEach.call(nodeList, node => {
  // do something
})

Most browsers (except IE) actually support the forEach method directly on NodeLists:

nodeList.forEach(node => {
  // do something
})

You can also use a for/while loop and access the individual elements using square bracket syntax:

for (let i = 0; i < nodeList.length; i++) {
  // current element is nodeList[i]
}
djfdev
  • 5,747
  • 3
  • 19
  • 38