0

In essence the function would contain a jQuery selection based on the id that is passed as argument. I recall seeing some code where $x was used to execute jQuery as if it was the selection.

I want to pass an element id to a function that executes jQuery using that selection. Sort of like

function doit(elname) { 
     $x=???; 
     $x.attr(); 
}

or something like this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

Use string interpolation with jQuery selector:

$(`#${idAsParan}`).hide();

Note use of ` character, instead of ' or ". Normally the top left key to the left of '1'.

Neil W
  • 7,670
  • 3
  • 28
  • 41
0

Consider the following Event based example.

$(function() {
  function myFunction(event) {
    var $el = $(event.target);
    $el.prop("disabled", true);
    console.log("Disabled " + $el.attr("id"));
  }

  $("button").click(myFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
<button id="button-3">Button 3</button>
<button id="button-4">Button 4</button>

This uses the event to select the target. So event.target is the target element and using $(event.target) creates it as a jQuery Object.

If you want to pass in a String, you can do that. It might look like this.

$(function() {
  function myFunction(elemId) {
    var $el;
    if (typeof elemId == 'string') {
      $el = $("#" + elemId);
    } else {
      $el = $(elemId);
    }
    $el.prop("disabled", true);
    console.log("Disabled " + $el.attr("id"));
  }

  $("button").click(function() {
    myFunction($(this).attr("id"));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
<button id="button-3">Button 3</button>
<button id="button-4">Button 4</button>
Twisty
  • 30,304
  • 2
  • 26
  • 45