[英]How to add innerHTML to div if another div is empty only using javascript
I have a issue about javascript. 我有一个关于javascript的问题。 I want to add innerHTML to div if it is empty. 我想将innerHTML添加到div(如果为空)。 This is my code, please help me review. 这是我的代码,请帮助我检查。 All div are the same class, not use id and only using javascript. 所有div都是同一个类,不使用id,仅使用javascript。 Thanks html: 谢谢html:
<div class="B">Test</div> <br/>
<div class="B"></div> <br/>
javascript: JavaScript的:
function test(){
var x = document.getElementsByClassName("B");
for (i = 0; i < x.length; i++) {
if (x[i].length() < 0){
x[i].innerHTML = "add test";
}
}
}
You need to use x[i].innerHTML.length
instead of x[i].length()
and it wont be less then zero at minimum it would be zero. 您需要使用x[i].innerHTML.length
而不是x[i].length()
,它至少不会小于零 ,而至少是零。
Few of corrections which I made in your code 我在您的代码中所做的一些更正
function test(){
var x = document.getElementsByClassName("B");
for (i = 0; i < x.length; i++) {
if (x[i].innerHTML.trim().length == 0){
x[i].innerHTML = "add test";
}
}
}
A jquery solution: 一个jQuery解决方案:
$('.B').each(function() {
var that = $(this);
if (that.text().length == 0) {
that.html('add test');
}
});
DEMO DEMO
The last two divs with class B that do not have any text will get filled with string add test
B类的最后两个div没有任何文本,将使用字符串add test
填充
$('.B').each(function() { var that = $(this); if (that.text().length == 0) { that.html('add test'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="A">testA</div> <div class="B">testB</div> <div class="B"></div> <div class="B"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.