Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Add class to child element but not to parent

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #187884
    Anonymous
    Inactive

    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.

    #187887
    shaneisme
    Participant

    Well 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.

    #187888
    Anonymous
    Inactive

    The 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

    #187889
    shaneisme
    Participant

    Well 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.

    #187895
    __
    Participant

    return false is overkill here, and can have unintended side effects. I suspect you’re looking for .stopPropagation…?

    http://codepen.io/adrian-enspired/pen/fytgh

    #187921
    Anonymous
    Inactive

    stopPropagation works.

Viewing 6 posts - 1 through 6 (of 6 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.