Jquery how to take the text of a paragraph?

1

Jquery how to take the text of a paragraph that does not have id when there are several | in the document. example:

<p> este es el texto </p>
<p> este es el 2º texto</p> 
var texto=$('p').text();
$("#muestra").append(texto);
console.log(texto);

I've done it with this code, but take the text of all the paragraphs:
with javascript to do it, with jquery no.

    
asked by Pedro Robles Ruiz 13.01.2018 в 11:21
source

1 answer

1

In jQuery you have selectors to be able to select the first element (with the suffix :first ), the last one (with the suffix :last ) or the one that is in a certain position (with the suffix :eq(index) ):

$(function(){
  // Coger el primero
  var texto= $('p:first').text();
  console.log('Primer párrafo: ', texto);
  // Coger el último
  texto= $('p:last').text();
  console.log('Último párrafo: ', texto);
  // Coger un ínice determinado (por ejemplo el índice 1: 2º elemento)
  texto= $('p:eq(1)').text();
  console.log('Segundo párrafo: ', texto);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> este es el texto </p>
<p> este es el 2º texto</p>  

<span id="muestra"></span>
    
answered by 13.01.2018 / 11:33
source