1
votes

On a website I have a button that is either "Log in" or "Log out" shown below

<button id="userLogBtn" class="user-log-in-log-out-2" data-wf-user-logout="Log out" data-wf-user-login="Log in" type="button">Log out</button>

The type="button" is either >Log out< or >Log in<.

How do I read the HTML to see if it is Log out

So far using something like this is not working

if (document.getElementById('userLogBtn').innerHTML.indexOf(">Log in<") = -1) 
1
Using the text content of an element to determine behavior is a bad idea. Give the button a class value to indicate its state. That will be independent of the choice of wording for the text, and will work even if you translate the content to another language. - Pointy
It maybe that your HTML doesn't parse in the state it's in. Use entities for the arrows: &gt;Log out&lt; for example. - Andy
1. = is for assignment, setting the value of something. You should be getting an error for the assignment shown, since you can't assign to the result of a function call. If you used == or ===, the the condition would be true if the button did not have the text ">Log in<" in it. 2. And indeed, it won't, because it looks like your button's text is "Log in" (no ><) or "Log out". - T.J. Crowder

1 Answers

-1
votes

Try checking equality of textContent instead of the innerHTML.

document.getElementById('userLogBtn').textContent === "Log in"

innerHTML represents the things inside the tag, between the > and <, so they won't show up in the returned string. textContent returns and innerHTML will be the same in this case (the real fix is === "Log in"), but textContent returns only the text, which is what you want. innerHTML also returns the HTML of any elements inside the button (which there shouldn't be).