将jQuery parent()和siblings()调用转换为纯Javascript

时间:2015-08-17 13:53:21

标签: javascript jquery

我遇到了一些麻烦,我正在处理的网站与jQuery存在冲突,我不知道如何将其转换为Javascript,或者是否有可能:

$(document).ready(function(){
   $('div.links').parent('td').siblings().find('a.schedule')
});

1 个答案:

答案 0 :(得分:3)

这很冗长,但JS冗长是我们都喜欢jQuery的一个原因:

var links = document.getElementsByClassName('links');

var hrefs = [];

for ( var i = 0; i < links.length; ++i )
  {
    var n = links[i];
    var pn = n.parentNode;
    
    if (n.parentNode.tagName.toLowerCase() == 'td')
      {
        var sib = n.parentNode.nextElementSibling;
        if (sib && sib.tagName.toLowerCase() == 'td')
          {
            var as = sib.getElementsByClassName('schedule');
            
            for ( var j = 0; j < as.length; ++j )
              hrefs.push(as[j]);
          }
      }     
  }

// highlight what we've found
for ( i = 0; i < hrefs.length; ++i )
  hrefs[i].className = 'selected';
.selected {
  background-color: yellow;
}
<table>
  <tr>
    <td><div class="links">links</div></td>
    <td><a href="#" class="schedule">schedule</a></td>
  </tr>
  <tr>
    <td></td>
    <td><a href="#" class="schedule">schedule</a></td>
  </tr>
  <tr>
    <td><div class="links">links</div></td>
    <td><a href="#" class="schedule">schedule</a></td>
  </tr>
  <tr>
    <td><div class="links">links</div></td>
    <td><a href="#" class="schedule">schedule</a></td>
  </tr>
  <tr>
    <td></td>
    <td><a href="#" class="schedule">schedule</a></td>
  </tr>
</table>