如何访问具有图像的td's而无需在td..中使用id或class

How to access the td's having images without using id or class in the td..?

本文关键字:td class id 访问 何访问 图像      更新时间:2023-09-26

我们有一个像这样的HTML时事通讯....

<table width="600">
<tr>
  <td>
     Text
  </td>
</tr>
<tr>
  <td>
     <img src="demo.jpg" width="200" height="200"/>
  </td>
</tr>
<tr>
  <td style="font:arial;">
     <img src="demo.jpg" width="200" height="200"/>
  </td>
</tr>
<tr>
  <td style="font:arial;">
   <a href="#">
     <img src="demo.jpg" width="200" height="200"/>
   </a>
  </td>
</tr>
</table>

我需要为具有图像的td添加style="font-size:0%"。我们没有在HTML中使用id或任何类。那么如何使用javascript ?? ?

谢谢! !

使用.has():

var $tds = $('td').has('img').css('font-size',0);
$('td:has(img)').css('font-size','0%');

var tds = document.getElementsByTagName('td');
for (var i=0; i<tds.length; i++) {
    if ( tds[i].getElementsByTagName('img').length )
         tds[i].style.fontSize = 0;
}

我建议使用一种稍微不同的方法,使用jQuery:

// note: 0 doesn't require a unit
$('img').closest('td').css('font-size', '0');

不使用jQuery的幼稚方法

var table = document.getElementsByTagName("table"),
    tds = document.getElementsByTagName("td"),
    tdsWithImages = Array.prototype.slice.call(tds).filter(function (td) {
        return td.getElementsByTagName('img').length > 0
    });
    tdsWithImages.map(function (td) {
        td.style.fontSize = "0";
    });

为什么不呢?$ (" td img) . each ()

$('img').closest('td').css('font-size','0%');