简体   繁体   中英

Transform jQuery function to pure JavaScript

How can I transform this code written in JQuery to just JS?

Original code:

$('.abcClass').each(function () {
    $(this).html($(this).text().replace(/([^\x00-\x80]|\w)/g, "<span class='mail'>$&</span>"));
});

I've tried to write it like this:

document.querySelectorAll('.abcClass').forEach(function (comment) {
    comment.innerHTML(comment.toString().replace(/([^\x00-\x80]|\w)/g, "<span class='mail'>$&</span>"));
});

But I've received the errors:

Uncaught TypeError: comment.innerHTML is not a function
Uncaught TypeError: Cannot read property 'classList' of null

I'm new to jQuery so I found myself pretty much stuck at this step... any help would be appreciated! :)

While .innerHTML is a function underneath, it's a setter (and getter), so you have to set and retrieve its values as if it was a plain property value:

comment.innerHTML = comment.innerHTML
  .replace(/([^\x00-\x80]|\w)/g, "<span class='mail'>$&</span>"));

Also keep in mind that querySelectorAll returns a NodeList, and NodeLists only have a forEach method in newer browsers (mid-2016+ or so). For better backwards compatibility, consider calling Array.prototype.forEach :

Array.prototype.forEach.call(
  document.querySelectorAll('.abcClass'),
  function(comment) {
    // ...

(pretty sure you can also do NodeList.prototype.forEach = Array.prototype.forEach beforehand, but that looks really weird to me)

Instead of using jquery .each()

$('div').each(function(){ //... })

use document.querySelectorAll(), then convert the HTMLCollection into a JavaScript array. Then you can map over the array of elements.

 const elems = document.querySelectorAll('.my-elements')
 const $elems = [].slice.call(elems)
 $elems.map( (elem) => { console.log(elem) })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM