最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Native JavaScript alternative for jQuery's next() - Stack Overflow

programmeradmin2浏览0评论

I have this code:

$.each(this.items, function(key, item) {
    item = $(item);
    item.css('background', 'red');
    item.next().css('display', 'none');
}

Now, I need to rewrite it in pure JavaScript so I am doing this

document.getElementById(aItems[iCount].id).style.background = 'red';
document.getElementById(aItems[iCount].id).style.display = 'none';

The problem is that display:none must be set for the next() item, not this one, how do I do this?

Thank you.

I have this code:

$.each(this.items, function(key, item) {
    item = $(item);
    item.css('background', 'red');
    item.next().css('display', 'none');
}

Now, I need to rewrite it in pure JavaScript so I am doing this

document.getElementById(aItems[iCount].id).style.background = 'red';
document.getElementById(aItems[iCount].id).style.display = 'none';

The problem is that display:none must be set for the next() item, not this one, how do I do this?

Thank you.

Share Improve this question edited Oct 11, 2014 at 12:20 T J 43.2k13 gold badges86 silver badges142 bronze badges asked Jan 7, 2013 at 14:12 LittlebobbydroptablesLittlebobbydroptables 3,7319 gold badges52 silver badges81 bronze badges 1
  • possible duplicate of Get next/previous element using Javascript – T J Commented Oct 11, 2014 at 12:21
Add a ment  | 

3 Answers 3

Reset to default 12

Try this:

item.nextSibling.style.display = 'none'

Keep in mind that nextSibling might select the text content next to the element, so you may need to use:

item.nextSibling.nextSibling.style.display = 'none'

Another option would be to use nextElementSibling, as Bergi suggested. However, that's not supported in all browsers, yet. You can create the function yourself, though:

function nextElementSibling(element) {
    do { 
        element = element.nextSibling;
    } while (element && element.nodeType !== 1);
    return element;
}

In this case:

nextElementSibling(item).style.display = 'none';

Last but not least, I'd suggest having a look at Palash' answer if you want to replace jQuery's $.each() with native JS.

You can use the nextElementSibling property of the selected DOM node:

var item = document.getElementById(aItems[iCount].id);
item.style.background = 'red';
item.style.display = 'none';
if (item.nextElementSibling)
    item.nextElementSibling.style.display = 'none';

You can also try this:

for(var iCount = 0; iCount < aItems.length;i++)
{
     var current = aItems[iCount].id;
     var next = aItems[iCount + 1].id;
     if ( next != null ) {
          document.getElementById(current).style.background = 'red';
          document.getElementById(next).style.display = 'none';
     }
}
发布评论

评论列表(0)

  1. 暂无评论