There was a task to eradicate jQuery from a script and immediately came across a problem.

There is a code:

function showContent(users) { var data = JSON.parse($(users).closest('.user').attr('data-json')); } 

The object enters $ (users):

Object content

What is the alternative to pure javascript for:

 $(users).closest('.user').attr('data-json') 

?

  • what is users ? - Grundy
  • function showContent(users) { var data = JSON.parse($(users).closest('.user').attr('data-json')); } function showContent(users) { var data = JSON.parse($(users).closest('.user').attr('data-json')); } Object comes into users - ProstoJohn 8:26 pm
  • Add this code to the question, as well as the object object comes in users - what kind of object? - Grundy
  • I don’t know how else to explain :) drive.google.com/file/d/0B4YdjUeWDSP8eHhIbTlNS2F6bG8/… - ProstoJohn
  • You can edit the question. - Grundy

1 answer 1

The analogue for attr with one parameter is the getAttribute function.

There is no analogue for the closest function, but you can write a function with a similar functional.

What the closest function does: for each element in the set, it searches for the first element that matches the specified rule, starting with the element itself and going up the DOM hierarchy.

If you simplify to the case of finding an element with a class, you can get the following function

 function closest(element, c){ var curElement = element; while(curElement && !curElement.classList.contains(c)) curElement=curElement.parentElement; return curElement; // вернет null если ничего не найдет } 
  • But what does the beginning mean: $ (users)? - ProstoJohn
  • @ProstoJohn, in general, is getting a jQuery object. but since you already get it as a parameter. it was possible to simply use users - Grundy
  • That's where the problem comes out .. When I try to write just users get this: TypeError: users.closest (...). Attr is not a function - ProstoJohn
  • @ProstoJohn, without knowing what exactly is being transmitted as users , and what versions of libraries are used can hardly say something about the error, except that users.closest(...) returned an object without the attr method - Grundy
  • Here you can write in HP? - ProstoJohn