skip to Main Content

Need to add a CSS class/ID in a dynamically generated content. The following fiddle is a sample format which is dynamically generated.

https://jsfiddle.net/g092zo3p/

<ul>
  <li><a href="#">Tab</a></li>
  <li><a href="#">Video</a></li>
  <li><a href="#">Accessory</a></li>
</ul>

I cannot edit the generated HTML. Hence I want to add a class to <li> via javascript. The class name should be the content inside the <a> link. Lets say in the first two <li> I want to add a class name which is the same as the content within the <a> tag.

e.g., <li class="Video"><a href="#">Video</a></li>

I tried search for it on good and all.

Thank you.

2

Answers


  1. Here’s my logic.

    • I forEach the anchor tag then i access the content inside it.
    • I find the parent of the anchor tag then pass the content value and use it as class.

    You can check it in DevTools or inspect elements.

    Just let me know if you have question..

    const anchorTag = document.querySelectorAll('ul li a');
    
    anchorTag.forEach(x => {
       $(x).parent().addClass(`${x.textContent}`);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
    <li><a href="#">Tab</a></li>
    <li><a href="#">Video</a></li>
    <li><a href="#">Accessory</a></li>
    <li><a href="#">Tab</a></li>
    <li><a href="#">Specification</a></li>
    <li><a href="#">Accessory</a></li>
    </ul>
    Login or Signup to reply.
  2. No Javascript Solution

    As Nathaniel Flick suggested, you can add class when you generate your dynamic list. For PHP it can be like this:

    <ul>
    <?php
    $array_with_list_values = ['Tab', 'Video', 'Accessory'];
    for ($i = 0; $i < count($array_with_list_values); $i++) {
    ?>
    <li class="<?= $array_with_list_values[$i]; ?>"><a href=""><?= $array_with_list_values[$i]; ?></a></li>
    <?php } ?>
    </ul>
    

    No need in javascript and Jquery.

    What if it is a plugin?

    Make a copy of plugin files, change PHP code related to the generation of the list (see example above), rename your copy of plugin and activate it, deactivate original plugin (as suggested here: Override Plugin Function in WordPress).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search