Get text from an element

-1

I'm trying to do a basic validation in pure javascript.

It works as follows; I have <h1> where the user profile is informed and I need to verify the text, as an example:

<h1 class="perfil-usuario">SISTEMA<h1>

And I also have the condition:

 <script>

  var perfilSistema = document.querySelector(".perfil-sistema");

  if (perfilSistema  == 'SISTEMA' ) {
    window.location = "index.html";
  }
 </script> 

But it is not directing the user to the index when it receives SYSTEM. Grateful to whom to help.

    
asked by anonymous 05.02.2018 / 21:25

3 answers

0

Firstly you have an error in your code, you should close the h1 tag like this: </h1>

  var perfilSistema = document.getElementById("psistema");
  var text = perfilSistema.innerHTML;
  alert(text);
  
  if (text  == 'SISTEMA' ) {
   alert('estou dentro do if, vou redirecionar'); 
   window.location = "index.html";
  }
<h1 class="perfil-usuario" id='psistema'>SISTEMA</h1>

Explanation of the code:

This is to get the html from within h1:

var text = perfilSistema.innerHTML;

and this was used to get the element with id pSistema

var perfilSistema = document.getElementById("psistema");
    
05.02.2018 / 21:35
0

There are two problems with your code. The first is that the query for this class will return null since it is searching for .perfil-sistema when the class name in your html is .perfil-usuario .

In addition, you are comparing an object with a string. You should compare the "content" (in this case, the "text") of the element with Node#textContent or Element#innerHTML() :

var perfilSistema = document.querySelector(".perfil-usuario");

if (perfilSistema.textContent == 'SISTEMA') {
  window.location = "index.html";
}
<h1 class="perfil-usuario">SISTEMA<h1>
    
05.02.2018 / 21:31
0

Paste these lines into your code and test

With pure Javascrip

  var cel = document.querySelector('.perfil-usuario').textContent; 
 if(cel == "SISTEMA"){
 alert("USER ENCONTRADO");
 window.open('http://www.google.com.br', '_self');
 //ou use  window.location = 'https://www.google.com.br' 
 }
 if(cel!="SISTEMA"){
 alert("USER NÃO ENCONTRADO");

 }

With jJquery

var cel = $('.perfil-usuario').text(); 
     if(cel == "SISTEMA"){
     alert("USER ENCONTRADO");
     open('http://www.google.com.br', '_self');
     }
     if(cel!="SISTEMA"){
     alert("USER NÃO ENCONTRADO");

     }
    
05.02.2018 / 21:30