Home > Enterprise >  How to refer to selected jQuery element in another function?
How to refer to selected jQuery element in another function?

Time:03-09

excuse me for my beginner question. Looking at this example:

$("#el4").html(`<b>${$("#el4").text()}</b>`);

I want to make text of the selected element bold. At the start of the line I selected $el4, then using html() I will replace the text with <b></b> tags. Between those tags I want to inject the current text of the element, but to do so I have to select the same element again using it's ID $("#el4").

Is it possible to somehow refer to the element that I am already working on? Something other than storing it in variable.

Thank you for your time!

CodePudding user response:

jQuery's .html() accepts a function so you can use that to reference the element. The functions arguments are index and the html string. If you do not want to use the html, you can use this and reference the element it is working on.

$("#el4").html(function(_,html){
  return `<b>${html}</b>`;
});


$("#el5").html(function(_,html){
  return `<b>${$(this).text()}</b>`;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="el4">Hello</p>

<p id="el5">WORLD</p>

CodePudding user response:

So this code as @epascarello said does work:

$("#el4").html(function(){ return `<b>${$(this).text()}</b>`; }); 

but the same code with an arrow function doesn't:

$("#el5").html(() => `<b>${$(this).text()}</b>`); 

Arrow function does in fact work when I select this element manually again using $("#el5"). Does that mean keyword this is pointing at different things in regular function and arrow function? Gotta read up on this..

Thanks to everyone that answered so quickly. It's my first post on stackoverflow and I am amazed by the response =)

  • Related