Reputation: 63
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 :)
Upvotes: 2
Views: 8485
Reputation: 11
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
Upvotes: 1
Reputation: 388316
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
Upvotes: 4
Reputation: 85545
Remove the hash(#): in javascript you don't need to use #
when selecting id.
document.getElementById('id_of_element').getElementsByTagName('div').addClass('some_class');
Upvotes: -1