简体   繁体   中英

Changing where to put text

I have a very basic if statement and it reads like this:

var p1 = document.getElementById('p1').value;
var p2 = document.getElementById('p2').value;

if(p1==p2){
    document.write("P1=P2");
} else {
    document.write("P1 Does Not Equal P2")
};

Followed by the following HTML

<p id="p1">2</p>
<p id="p2">4</p>

I just want to be able to identify the if the value within p1 is greater or less than the value of p2 . Eventually this will have bigger consequences than just document.write but at this time the if statement does not recognize the content in between the <p></p> .

p tags do not have a value. You can get the innerHtml and compare that instead:

var p1 = document.getElementById('p1').innerHtml;
var p2 = document.getElementById('p2').innerHtml;

Paragraph tags don't have a value, so you would need to use innerHTML.

var p1 = document.getElementById('p1').innerHTML;
var p2 = document.getElementById('p2').innerHTML;

if(p1==p2){
    console.log("P1=P2");
} else {
    console.log("P1 Does Not Equal P2")
};

However, that doesn't solve the 2nd part of the problem, since you mention that eventually you will need to know > or <, also. To make that happen, you would can change your tags to something else (a div?) or convert the resulting values to numbers.

var p1 = document.getElementById('p1').innerHTML;
var p2 = document.getElementById('p2').innerHTML;

var v1 = Number(p1);
var v2 = Number(p2)

console.log(p1);
console.log(p2);
console.log(v1);
console.log(v2);

if(v1==v2){
    console.log("P1=P2");
} else {
    console.log("P1 Does Not Equal P2")
};

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