Home > front end >  How to refer to the target in jQuery DOM manipulation?
How to refer to the target in jQuery DOM manipulation?

Time:10-17

I would like to add elements after the selected elements using jQuery, and say I would like to generate a new element with the same name as the target.

$("input:checkbox").after("<input type='hidden' name='...' value='...'/>");

I suppose I have to do this with string concatenation:

$("input:checkbox").after("<input type='hidden' name='"  <how to refer here to the target?> "' value='...'/>");

Question

How can I refer to the actual target in the parameter expression of after()? When using jQuery event listeners, I know I got the event, and its target property will be the DOM element, but here I am stuck

CodePudding user response:

With each, you get a callback, from which you can reference the element iterated over.

$("input:checkbox").each(function() {
  // `this` now refers to the input

  // maybe you want something like
  $(this).after("<input type='hidden' name='"   this.name   "' etc
});

Show code snippet

$("input:checkbox").each(function() {
  $(this).after("<input name='"   this.name   "'>");
});
console.log(document.body.innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="foo">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related