简体   繁体   中英

Javascript If Statement for Text between two Tags

I am trying to write a javascript function with an "if" statement that will execute a command if the text between two tags match. I have been able to write many "if" statements in which a command is executed when the value within an input textbox equals that of the "if" statement criteria such as:

function Test()
{
    if (document.getElementById('A').value == 1)
    {
      alert('test');
    }
}

<input type="button" id="B" onCLick="Test()"/>
<input type="text" id="A"/>

When I enter "1" in the textbox and press the button, an alert box will appeare. The problem that I am having is that I would like to do the same with text bewteen two tags. For example:

function Test()
{
        if (document.getElementById('A').value == 1)
    {
      alert('test');
    }
}

<input type="button" id="B" onCLick="Test()"/>
<p id="A">1</p>

In my project I would be using words instead of numbers, so I understand that I would have to surround the word in quotes. Unfortunately, this doesn't work. Is it possible to write an "if" statement like the one above that determines if text between two tags is true? Also, I have tried document.getElementById('A').text, and document.getElementById('A').innerHTML, but none of those made a difference. I ave even tried using one equal sign instead of two; however, that would make all criteria true, regardless if it were true or not.

Thanks

DFM

if(document.getElementById("myID").innerHTML == "1")

Would evaluate to true if the element in question (eg a div) had the following markup.

<div>1</div>

You could also use jQuery

if($(element).text() == "1")

You have onCLick instead of onclick (all lowercase) in your second example, which is why it is not working. You should use innerHTML to get the text inside the <p> element.

Note however, that were you to have other elements inside of an element that you wanted to get the text for, using innerHTML will return all of those elements and their respective content too.

Working Demo

This should do what you want.

<html>

  <input id="test" type="text" value="hello">

  <script>
    if (document.getElementById('test').value == "hello") alert("hello");
  </script>

</html>

It's been a couple years since I've been deep in JavaScript development, but as I recall (a bit rusty), instead of innerHTML, it's better to use stuff like childNodes[0].nodeValue or firstChild.nodeValue for

tags like that.

Refer to the following link... http://www.howtocreate.co.uk/tutorials/javascript/dombasics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM