Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen using jQuery.attr() to set an attribute the browser doesn't update the style from the css
    primarykey
    data
    text
    <p>I have a site hat lists a set of files that can be downloaded. The custom attribute docType is set based on the file extension. If there is no extension the docType is set to "unknownDoc". The CSS file looks similar to this:</p> <pre><code>.TitleColumn[docType="pdf"] { background: url("/images/common/icons/pdf.png") no-repeat left center; } .TitleColumn[docType="doc"], TitleColumn[docType="docx"] { background: url("/images/common/icons/word.png") no-repeat left center; } .TitleColumn[docType="unknownDoc"] { background: url("/images/common/icons/unknownDoc.png") no-repeat left center; } </code></pre> <p>It's quite possible that a user will upload a document that we don't have a css style set up for yet. In this case the item will have a docType but no background-image. In these cases I want the unknownDoc style to be applied. So I use the following:</p> <pre><code>$('.TitleColumn').each(function (index) { var hasNoDocImage = $(this).css("background-image") == "none"; var docType = $(this).attr("docType"); if (hasNoDocImage &amp;&amp; docType) { $(this).attr("docType", "unknownDoc"); $(this).addClass("TitleColumn[docType=\"unknownDoc\"]"); } }); </code></pre> <p>This works fine. What I don't understand is why do I have to use the addClass statement? The attr or addClass by themselves does not work. It's as if adding the attribute doesn't cause the browser to re-style the item based on the new attribute like addClass does. Is this a jQuery thing or a browser thing?</p> <p>Is there a better way to do this?</p> <p>I tried using just classes rather than the docType custom attribute but it gets too messy, especially when additional classes may be added to the element in the future.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload