How to get a value of a li?

1

I have the following structure:

<span class="ErrorViewer">
 <menu>
   <li>El Porcentaje de la prima del contrato es menor que el porcentaje Aprobado por la GERENTE </li>
 </menu>

I would like to show an alert with the text that is within <li> using JS or JQuery

    
asked by N. Zaldivar 24.06.2016 в 00:24
source

3 answers

1

Well then assuming that the "error" will be dynamic ( to say it in some way ) then we will do the following:

/*Todo esto código solo es para silumar cuando se lanza el error*/
var btn = document.getElementById("lanza");
btn.onclick = function(){
   var spanError = '<span class="error"><menu><li>texto del error</li></menu></span>';
   this.insertAdjacentHTML('afterend',spanError);
}

var btnSaludo = document.getElementById("saludo");
btnSaludo.onclick = function(){
  var spanSaludo = '<span class="saludo"><menu><li>HOLA COMO ESTAS</li></menu>';
  btn.insertAdjacentHTML('afterend',spanSaludo);
}
/*Aqui termina digamos el simulador; cuando sale el error*/
/*Ahora si comenzamos con el código que debes mas centrarte
Pues bien, creamos un Event Listener donde vamos a agregarselo a todo el body danto como evento los clicks
*/
document.querySelector('body').addEventListener('click', function() { //cuando se ejecute un click en el body entra esta función anonima
  var a = document.querySelector("span.error"); //Buscamos si tenemos en el documento algun elemento span con una class .error
  if(a != undefined || a != null){ //Confirmamos que si haya un elemento
      alert(a.outerText); //Cuando si encontremos un elemento, entonces lanzamos un alert con el texto que se contiene en el elemento li
  }
});
<button id="lanza">lanzar error</button>
<button id="saludo">lanzar saludo</button>

Now, it does much more than coding this code, but you can now tropicalize it to your needs.

    
answered by 24.06.2016 / 01:30
source
0

To get the text of the <li> tag add an id to it and then use the function text() of jquery for example:

alert($("#demo").text());
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<span class="ErrorViewer">
 <menu>
   <li id="demo">El Porcentaje de la prima del contrato es menor que el porcentaje Aprobado por la GERENTE 
   </li>
 </menu>
</body>
</html>
    
answered by 24.06.2016 в 00:31
0

Bone something like this

alert($("span.ErrorViewer menu li").text())
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<span class="ErrorViewer">
 <menu>
   <li>El Porcentaje de la prima del contrato es menor que el porcentaje Aprobado por la GERENTE </li>
 </menu>

Here we will bin the click event to all the li , which are within the el% menu and with the this and text() we send their value to alert

    
answered by 24.06.2016 в 00:29