Javascript if expression 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 the two tags matches. I could write a lot of β€œif” statements in which the command is executed when the value in the input text field is equal to the value of the criteria of the β€œif” expression, for example:

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 text box and click the button, a warning window will appear. The problem I am facing is that I would like to do the same with text containing two tags. For instance:

 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 use words instead of numbers, so I understand that I will have to surround the word in quotation marks. Unfortunately this does not work. Is it possible to write an "if" statement, as described above, which determines whether the text between two tags is true? In addition, I tried document.getElementById ('A'). Text and document.getElementById ('A'). InnerHTML, but none of them made a difference. I even tried using one equal sign instead of two; however, this will make all criteria true, regardless of whether they were true or not.

thanks

DFM

+4
source share
4 answers

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> 
0
source
 if(document.getElementById("myID").innerHTML == "1") 

Will evaluate to true if the item in question (such as a div) has the following markup.

 <div>1</div> 

You can also use jQuery

 if($(element).text() == "1") 
+4
source

You have onCLick instead of onCLick (all lowercase letters) in the second example, so it doesn't work. You must use innerHTML to get the text inside the <p> element.

Note that you had other elements inside the element for which you wanted to receive text, using innerHTML also return all these elements and their contents.

Working demo

+2
source

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

.

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

0
source

All Articles