How to get first nth-child or first-child with span using jQuery

3

I wanted to have the first nth-child, which is filled dynamically by aggregation and I do not know how to get it.

$("ul > li > a > span.menu-item-text:nth-child(1)").text("Primer Inicio");
ul { 
  padding: 0;
  margin: 0;
}

ul > li {
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="test static">
      <li class="static">
        <a href="#">
          <span class="menu-item-text">Frist (solo quiere cambiar "Primer Inicio")</span>
        </a>
      </li>
      <li class="static">
        <a href="#">
          <span class="menu-item-text">Two</span>
        </a>
      </li>
      <li class="static">
        <a href="#">
          <span class="menu-item-text">Tree</span>
        </a>
      </li>
    </ul>
    
asked by Diego Sagredo 25.01.2017 в 14:46
source

3 answers

3

To complete the other answers and see your code, here are some reference examples with different possibilities:

  • :first - $('.menu-item-text:first').text("Primer Inicio");
  • :eq() - $('.menu-item-text:eq(0)').text("Primer Inicio");
  • :lt() - $('.menu-item-text:lt(1)').text("Primer Inicio");
  • .filter() - $('.menu-item-text').filter(':first').text("Primer Inicio");
  • .children() - $('ul a').children(':first').text("Primer Inicio");
  • .first() - $('ul a span').first().text("Primer Inicio");
answered by 25.01.2017 / 16:02
source
6

Your example does not work because all the span.menu-item-text are :nth-child(1) within each <a /> one option is that you use the selector :eq() :

$("ul > li > a > span.menu-item-text:eq(0)").text("Primer Inicio");

or apply :nth-child(1) to the list of <li/> :

$("ul > li:nth-child(1) > a > span.menu-item-text").text("Primer Inicio");
    
answered by 25.01.2017 в 15:12
4

Your problem is that you are getting all span that is first child and all span are first children (from to ). Instead you should get the first li and reference the span .

  

When you want to get the first child, just use the pseudo selector first-child

jQuery

$('ul li:first-child a span').text('Primer inicio');

JavaScript (pure)

document.querySelector('ul li:first-child a span').textContent = 'Primer inicio';

$('ul li:first-child a span').text("Primer Inicio");
ul { 
  padding: 0;
  margin: 0;
}

ul > li {
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="test static">
      <li class="static">
        <a href="#">
          <span class="menu-item-text">Frist (solo quiere cambiar "Primer Inicio")</span>
        </a>
      </li>
      <li class="static">
        <a href="#">
          <span class="menu-item-text">Two</span>
        </a>
      </li>
      <li class="static">
        <a href="#">
          <span class="menu-item-text">Tree</span>
        </a>
      </li>
    </ul>
    
answered by 25.01.2017 в 15:13