如何删除没有任何id的td

时间:2015-12-16 11:18:47

标签: javascript

enter image description here

你好我想删除"你曾在军队服役过吗?"和"不"如果答案是"否"但是当它会"是"应该表现出来。

无论我尝试了什么,但它没有工作

<script type="text/javascript">
(function(){
  for(i = 0; (a = document.getElementsByTagName("td")[i]); i++){
    if(document.getElementsByTagName("span")[i].innerHTML.indexOf('Have you served in the military') > -1){
    document.getElementsByTagName("td")[i].style.display = "none";
    }
  }
})();
</script>

3 个答案:

答案 0 :(得分:0)

你可以获得所有的td元素,而不是获取其中的span元素:

var tds = document.getElementsByTagName('TD');
for (var i = 0, l = tds.length; i != l; ++i) {
    var spans = tds[i].getElementsByTagName('SPAN');
    for (var j = 0, l2 = spans.length; j != l2; ++j) {
        var span = spans[j];
        if ((span.textContent = span.innerText).indexOf('Have you served in the military') != -1) {
            span.style.display = 'none';
            break;
        }
    }
}

编辑: OP只想删除内容为“否”的td(也删除td元素)

var tds = document.getElementsByTagName('TD');
var tdsLength = tds.length;

var answerNoFound = false;
for (var i = 0; i != tdsLength; ++i) {
    var td = tds[i];
    if ((td.textContent = td.innerText) == 'No') {
        td.style.display = 'none';
        answerNoFound = true;
        break;
    }
}

if (answerNoFound)
    for (var i = 0; i != tdsLength; ++i) {
        var spanFound = false;
        var spans = tds[i].getElementsByTagName('SPAN');
        for (var j = 0, l = spans.length; j != l; ++j) {
            var span = spans[j];
            if ((span.textContent = span.innerText).indexOf('Have you served in the military') != -1) {
                span.style.display = 'none';
                spanFound = true;
                break;
            }
        }
        if (spanFound)
            break;
    }

答案 1 :(得分:0)

您可以使用元素的子元素或只是执行查找替换甚至隐藏和显示。

答案 2 :(得分:0)

看起来你有一个申请表,document可能有更多的跨度,有些超出td元素,所以你没有正确选择spans与{{1 }}

因此,当您比较td内容时,很可能不是您的循环span内的span

td

我更改了if语句,在你的循环<script type="text/javascript"> (function(){ for(i = 0; (a = document.getElementsByTagName("td")[i]); i++){ if(a.getElementsByTagName("span")[0].innerHTML.indexOf('Have you served in the military') > -1){ a.style.display = "none"; } } })(); </script> 中选择了span,应该这样做。