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

Adding class to all childrens(in first level o hierarchy) of specified element in javascript without jquery - Stack Overflow

programmeradmin8浏览0评论

I want to change this from jquery to javascript: $('#id_of_element').children('div').addClass('some_class');

So far all i have is this(not working):
document.getElementById('id_of_element').getElementsByTagName('div').addClass('some_class');

I have to change all my code from jquery to javascript. Is there any site with have examples of functions in javascript next to jquery? Thanks in advance for all help :)

I want to change this from jquery to javascript: $('#id_of_element').children('div').addClass('some_class');

So far all i have is this(not working):
document.getElementById('id_of_element').getElementsByTagName('div').addClass('some_class');

I have to change all my code from jquery to javascript. Is there any site with have examples of functions in javascript next to jquery? Thanks in advance for all help :)

Share Improve this question edited Dec 31, 2013 at 11:09 Marek Nijaki asked Dec 31, 2013 at 11:03 Marek NijakiMarek Nijaki 631 gold badge2 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Try

var el = document.getElementById('elem'),
    //modern browsers IE >= 10
    classList = 'classList' in el;
for (var i = 0; i < el.children.length; i++) {
    var child = el.children[i];
    if (child.tagName == 'DIV') {
        if (classList) {
            child.classList.add('test');
        } else {
            child.className += ' test'
        }
    }
}

Demo: Fiddle

If anyone wants to loop through all children, this worked for me:

const addClassList = (element) => {
  Object.values(element.children).forEach((e) => {
    e.classList.add('myClass');
    if (e.children.length > 0) addClassList(e);
  });
};

addClassList(myElement);

NOTE: Does not work with conditional rendering

Remove the hash(#): in javascript you don't need to use # when selecting id.

document.getElementById('id_of_element').getElementsByTagName('div').addClass('some_class');

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论