Reputation: 856
I need to put a text in a paragraph but just if is empty.
This is my JavaScript Function that doesn't works:
function myFunction(id,name) {
var var1=document.getElementById(id);
if(var1.text==null){
document.getElementById(id).innerHTML = name;
}}
I have this two paragraphs
<p id="1"></p>
<p id="2">Im not Empty</p>
Actually with the previous function both paragraphs acquire text but I need to put text in just the first of them.
This is php part, this part works. The problem is just in the JavaScript function.
<?php
$idVar=1;
$strVar="I was empty";
while($idVar<=2){
echo "<button onclick='myFunction(".json_encode($idVar).",".json_encode($strVar).")' type='button' id='botones'></button>";
$idVar++;
}
?>
Please help, thanks.
Upvotes: 0
Views: 940
Reputation: 30557
Use textContent and check if empty with ''
instead of null
function myFunction(id,name) {
var var1=document.getElementById(id);
if(var1.textContent==''){
document.getElementById(id).innerHTML = name;
}}
function myFunction(id, name) {
var var1 = document.getElementById(id);
console.log(var1.textContent);
if (var1.textContent == '') {
document.getElementById(id).innerHTML = name;
}
}
myFunction(1, 'test');
<p id="1"></p>
<p id="2">Im not Empty</p>
Upvotes: 1