2

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! :)

1

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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) })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.