Search code examples
javascripthtmlchildren

Select child when multiple parents with same class - Javascript


I would like to know you if it is possible with pure Javascript to select the child of every parent with the same class. For example:

<div class="parent">
    <a href="#" rel="category tag">Category1</a>
</div>
<div class="parent">
    <a href="#" rel="category tag">Category2</a>
</div>
<div class="parent">
    <a href="#" rel="category tag">Category1</a>
</div>
<div class="parent">
    <a href="#" rel="category tag">Category2</a>
</div>

EDIT:

In this case, I need to select the element of all the and change the background color based on the category: if the category is "Category1" background should be blue, if the category is "Category2" should be red and so on...


Solution

  • You could do something like this.

    By adding the class based on content.

    $('.parent a').each(function() {
         var className = $(this).html().replace(' ', '').toLowerCase();
         $(this).addClass(className);
    });
    .category1 {
      color: orange;
    }
    
    .category2 {
      color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <div class="parent">
        <a href="#" rel="category tag">Category1</a>
    </div>
    <div class="parent">
        <a href="#" rel="category tag">Category2</a>
    </div>
    <div class="parent">
        <a href="#" rel="category tag">Category1</a>
    </div>
    <div class="parent">
        <a href="#" rel="category tag">Category2</a>
    </div>