Home › Forums › JavaScript › Add class to child element but not to parent
- This topic is empty.
-
AuthorPosts
-
November 7, 2014 at 3:12 pm #187884AnonymousInactive
I want to add a class to one element at a time. The element may be a child of a parent element that the click event is also applied to. whats the best method to add the class to the child element only, but not the parent. Heres an example, click on the child div and see that the class is also added to all parent elements. I can think of a few ways to do this but I want to make sure Im using the best solution.
http://codepen.io/anon/pen/aiGJb
Basically I want the class to only be added to the element clicked regardless of its parents with the same class.
November 7, 2014 at 3:31 pm #187887shaneismeParticipantWell it’s doing exactly what you’re telling it to do! You have a class that’s
.element
on each and you’re telling jQuery to add a class to everything with a class of.element
.Now, you can do something like point to the ID instead:
'#childdd'
(negative points on semantic naming rules there), but that only works for that one element per page (since ID’s are unique)… or you can make a specific class name for what you want to be edited.It’s good practice to remove JS and CSS from each other, this means you should have JS-specific class names for things you’re going to manipulate with JS. So you can do something like
.js-click
on the one (or more) elements that you want to add the class to.November 7, 2014 at 3:35 pm #187888AnonymousInactiveThe content is extremely dynamic and giving ids is not an option. I was thinking of adding the element and then traverse up the dom to remove any other classes. Although I really want to see other methods
November 7, 2014 at 3:37 pm #187889shaneismeParticipantWell you have to start somewhere. So if ID’s aren’t an option (I wouldn’t recommend using them anyway), you’d need a unique class.
I guess I’d have to see the actual code you’re working with to help.
November 7, 2014 at 7:24 pm #187895__Participantreturn false
is overkill here, and can have unintended side effects. I suspect you’re looking for.stopPropagation
…?November 8, 2014 at 6:47 pm #187921AnonymousInactivestopPropagation
works. -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.