Javascript native equivalent to JQuery .each() & $(this)

后端 未结 4 1225
别跟我提以往
别跟我提以往 2021-01-04 21:47

I have the following code which looks at each div with class .comment and shortens the text if more than 100 characters. Using JQuery.

Question is how t

4条回答
  •  悲&欢浪女
    2021-01-04 21:48

    You're not going to find a native equivalent to $(this) because that is the jQuery function. There wouldn't be any reason to write the $ function if it already existed natively.

    As for the .each part, you can work with any array like this:

    var $comments = $('.comment');
    comments.forEach(function(comment) { ... });
    

    or using a simple for loop:

    for (var i = 0, len = $comments.length; i < len; i++) {
        var comment = $comments[i];
    }
    

    If you want to remove jQuery entirely, you'll need to get your elements using document.getElementsByClassName. This will return an HTMLCollection which does not have the forEach function so you'll need to use a for loop like above.

    Also note that you won't have access to the .html function. Instead, you can access and modify it with the .innerHTML property of each node.

    var comments = document.getElementsByClassName('comment');
    for (var i = 0, len = comments.length; i < len; i++) {
        var comment = comments[i];
        var content = comment.innerHTML;
        ...
        comment.innerHTML = html;
    }
    

    Update: 2019-12-02

    Nowadays it is more common to use document.querySelectorAll for querying elements and you can use Array.from if you would like to convert the NodeList to an array.

    function boldComments() {
      const comments = document.querySelectorAll('.comment');
      comments.forEach(comment => {
        comment.innerHTML = '' + comment.innerHTML + '';
      })
    }
    
    document.querySelector('button').addEventListener('click', boldComments);
    • Comment A
    • Comment B
    • Comment C
    • Comment D

提交回复
热议问题