search

Home  >  Q&A  >  body text

Remove HTML attributes without value

I have an R shiny app with a navigation bar from the R shiny package. However, I am interested in outputting HTML, so no R specific knowledge is required here.

Tabbing through this navigation bar will skip these entries if these tabs have been previously selected. This is because when a tab is selected, shiny adds class="active" to that tab's

  • element in the navigation bar. Then when you click the tab, it removes ="active", leaving only
  • . Is HTML valid based on empty class attribute? This is invalid HTML, which must be why tabbing through the navigation bar fails

    I want to remove these class targets that have no value. I tried to do this using jquery by adding

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

    Remove all these targets whenever a new tab is selected. However, I think this will cause some additional confusion, as other functionality in the app is now broken - predictably, this is a very brute force approach. The problem is that this HTML is invalid and I don't know how to select it correctly!

    It would be great if anyone could suggest a strategy for solving this problem. Thanks!

  • P粉797004644P粉797004644447 days ago549

    reply all(1)I'll reply

  • P粉401901266

    P粉4019012662023-09-07 14:23:10

    Use attributes for empty classes [] selector, for example: [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 this:

    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>

    No need to load the entire library.

    reply
    0
  • Cancelreply