skip to Main Content

I have an R shiny app with a navbar from the R shiny package. However, I’m interested in the output HTML so no R specific knowledge is required here.

Tabbing through this navbar skips entries when those tabs have previously been selected. This is because when a tab is selected shiny adds class="active" to the <li> element for that tab in the navbar. When you then click off the tab it takes away the ="active" and you’re left with just <li class>. According to Is an empty class attribute valid HTML? this is invalid HTML, and this must be why tabbing through the navbar is broken

I want to remove these class targets without a value. I tried using jquery to do this by adding

$(document).on('hide.bs.tab', (x) => {
    $('*[class!=*]').removeAttr('class');

to remove all these targets whenever a new tab is selected. However, I think this is causing some additional mayhem as other features in the app are now broken – to be expected at this is a very brute force approach. The problem is seeing as this HTML is invalid I’m not sure how to properly select it!

If anyone could advise on a strategy to deal with this that’d be great. Thanks!

2

Answers


  1. Use the attribute [] selector for empty class like: [class=""]

    $('[class=""]').removeAttr("class");
    [class] {
      background: red;
    }
    <div class="foo">class="foo"</div>
    <div class="">class=""</div>
    <div class>class</div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

    In pure JavaScript you would do it like:

    document.querySelectorAll('[class=""]').forEach(el => el.removeAttribute("class"));
    [class] {
      background: red;
    }
    <div class="foo">class="foo"</div>
    <div class="">class=""</div>
    <div class>class</div>

    without the need to load an entire library.

    Login or Signup to reply.
  2. you can do it like that

     <a class="x" id="myid">btn</a>   
     document.getElementById("myid").removeAttribute('class');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search