skip to Main Content

I am getting Dom text reinterpeted as HTML when trying to use (this) in JS script

I have a function

function test(item) {
     let newText = $(item).val()
      ... some more logic
}

$(".test").each(function(){
    //...somelogic
    test(this);
}

Now i get the warning at let newText = $(item).val()

how can we get rid of this warning i.e Dom text reinterpeted as HTML

2

Answers


  1. You can pass an index and element in the each function. Just pass the element and don’t use "this"

    function test(item) {
         let newText = $(item).val(); 
    }
    
    $(".test").each(function(idx, el){
        test(el);
    });
    

    But it’s hard to tell without a complete reproducible example what’s really going on with your code.

    Login or Signup to reply.
  2. If I add the missing ) at the end of your .each() function, comment out the "… some more logic" and add a console.log() call, the code you have posted here, runs without error. See the snippet:

    So like has already been said, you need to provide enough code to show what is producing the error.

    function test(item) {
         let newText = $(item).val()
          //... some more logic
          console.log(newText)
    }
    
    $(".test").each(function(){
        //...somelogic
        test(this);
    }
    // NOTE Missing trailing )
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <input type="text" class="test" value="One">
            <input type="text" value="Nada">
            <input type="text" class="test" value="Two">
            <input type="text" class="test" value="Three">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search