Home > Enterprise >  jQuery selector input[type=text]:nth-child(2) not working
jQuery selector input[type=text]:nth-child(2) not working

Time:12-10

I'm unable to use the ids or the class names associated with the inputs due to how they're randomly generated on input.

The render looks like this:

<div class='dateSearch'>
  <label>Label 1</label>
  <input type='text' id='random_id_1'/>
  <span>Icon</span>
  <input type='text' id='random_id_2'/>
  <span>Icon</span>
  <input type='button' id='searchBtn'/>
</div>

I have no control of the render and can not change any content. So instead I was trying to grab the second text input and add a label before it.

<script>
  $('<label>Label 2</label>').insertBefore('.dateSearch input[type=text]:nth-child(2)')
</script>

.dateSearch input[type=text] will add the label infront of both text inputs, but :nth-child(2) doesn't seem to want to work.

I've tried .dateSearch > input:nth-child(2) and that failed to work as well. I just wanted to add a label before the second input element.

  $('<label>Label 2</label>').insertBefore('.dateSearch input[type=text]:nth-child(2)')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<div class='dateSearch'>
  <label>Label 1</label>
  <input type='text' id='random_id_1'/>
  <span>Icon</span>
  <input type='text' id='random_id_2'/>
  <span>Icon</span>
  <button type="button" >Search</button>
</div>

Want it to look like this:

Label_1 [ Input Text ] (Icon) Label_2 [ Input Text ] (Icon) [ Button ]

CodePudding user response:

Are you familiar with eq()? That gets you around the child selector problem because you can target elements by type as well.

Don't forget to put a for attribute on the label for accessibility if you can.

const secondInput = $('.dateSearch input[type=text]').eq(1); // zero-based
const secondInputId = secondInput.attr('id'); // optional, but wise
const label = $('<label>Label 2</label>');
label.attr('for', secondInputId); // optional, but wise

label.insertBefore(secondInput);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class='dateSearch'>
  <label>Label 1</label>
  <input type='text' id='random_id_1' />
  <span>Icon</span>
  <input type='text' id='random_id_2' />
  <span>Icon</span>
  <button type="button" >Search</button>
</div>

  • Related