Using jQuery to Add a Class Attribute to images, etc. on Page?

19,365

Solution 1

jQuery has a built-in method for adding classes.

<script type="text/javascript" src="../jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("img[src*=menumain-]").addClass("menumain");

    });
</script>

http://api.jquery.com/addClass

Solution 2

You could put the images you want styling inside container divs, then do

$('.container').addClass('yourClass');

then in the class, use

.yourClass img {}

to style all of the images within those containers. It's a workaround, but it should fix your problem! Also, in HTML5, the use of type="text/javascript" within the <script> tags is no longer required.

Share:
19,365
BozoExplosion
Author by

BozoExplosion

Updated on July 20, 2022

Comments

  • BozoExplosion
    BozoExplosion almost 2 years

    Li'l Help? Apologies in advance due to my jQuery.noob status, but I'm drawing a blank and about out of ideas on why this isn't working. Maybe someone here can see something I'm not? I'd surely appreciate any help.

    The Issue

    This webpage has several images on it (also paragraphs, etc.) that I want to add a class to. They don't currently have a class on them.

    Why I want to Add a Class

    I want to use CSS3 to target that class and style anything that has it. More specifically this is going to be a pop-in menu and I'd like to adjust the opacity of it and animate its entry & exit.

    How I'm attempting to do This

    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $("document").ready(function() {
            $("img").addClass("menumain");
                       alert("Here I am!"); //This alert will go when I figure this out, I just added it to see if it pops up (it does).
        });
    </script>
    

    I've Also Tried it This Way (Note: All of my images contain the string "menumain-" in the file names)

    <script type="text/javascript" src="../jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $("document").ready(function() {
            $("img[src*=menumain-]").attr({class:"menumain"});
    
        });
    </script>
    

    So What Happens When I Try it?

    Nothing. I load the page, (that alert does pop up, which I dismiss) then expand out the body using firebug and / or Safari developer tools, etc. and drill down to the images on the page. I see the image attributes, but I don't see where the class was added, much less defined as "menumain" which is what I want the class to be.

    Part of Why This is Driving me Crazy

    I have another jQuery script on the same page which does something similar. It adds attributes, not a Class attribute, but other attributes to the main Div which surrounds the whole page. I don't have any problems with that jQuery function, so I don't see why this one isn't working.

    Why Might it Not Be Working

    I've checked the syntax 9 ways from Sunday, but I don't see anything wrong. Still, you know how proof reading syntax can be.

    Secondly the images I'm targeting (I'm also going to try to get the text and buttons in the menu tagged in this same class) are buried down in Divs like this:

    <div id="image194" style="visibility: inherit;">
         <a name="image194anc">
              <img width="317" height="564" border="0" alt="menumain-bg-317x564"    src="images/menumain-bg-317x564.png" name="image194Img">
         </a>
    </div>
    

    I'm assuming that my targeting of $("img[src=menumain-]")* will find those images whether they are in Divs or not, but maybe I'm wrong on that?

    One More Thing

    This "web page" is generated by an application called Lectora by Trivantis. It's a WYSIWYG authoring tool for instructional designers (who are NOT web developers) who create on line training. So it's not as if I'm creating this whole thing in DreamWeaver or can change the entire approach to the web design. But I should be able to pop a class on a set of page elements and target them with CSS, no?

    Please tell me if you see anything wrong. Here's a version of the page --> http://bit.ly/Rijnl8

  • Kevin B
    Kevin B almost 12 years
    Basically. His real problem is going to be somewhere else, such as whether or not the images exist at that point. This probably should have been a comment.
  • BozoExplosion
    BozoExplosion almost 12 years
    So the images, since they are part of a "pop up" menu (i.e. the menu is not visible until a button is clicked, then the elements that form the menu like the images and text all just "show up"), they aren't visible on the page when the page loads. Thus the $(document).ready function doesn't trigger the jQuery, because the images "aren't there." And when the menu pops in, nothing triggers the script. Is that about it?
  • Kevin B
    Kevin B almost 12 years
    The $(document).ready works, however $("img[src*=menumain-]") doesn't find any images because they aren't attached to the document is my guess. I haven't been to the link you provided to confirm.
  • BozoExplosion
    BozoExplosion almost 12 years
    Each of those images is in its own Div. I suppose it's possible to target the Div as in "$(Find me all Divs which contain an image which has a source that, itself, contains the string "menumain-"). Any hints on that syntax?
  • Kevin B
    Kevin B almost 12 years
    If $("img[src*=menumain-]") doesn't select any images, selecting the image's parent and then the images also won't select any images unless you have a direct reference to that div and the div is a document fragment.
  • BozoExplosion
    BozoExplosion almost 12 years
    So I'm thinking that $("div:contains(img[src*=menumain-])").addClass("menumain"); would add the class "menumain" to the Div. Which div? Any Div that contains an image which has a source that contains the string "menumain-"
  • Kevin B
    Kevin B almost 12 years
    Correct, however if the original selector didn't find any images, that one isn't going to find any divs that contain those images.
  • BozoExplosion
    BozoExplosion almost 12 years
    So, Kevin B, that won't select the image? Rats! 'Cause I thought that should query the images that use a source with that string in the source. What am I doing wrong, because that's what I'm trying to do. Those images have various attributes like height, width, etc. I need to add a class to those attributes. If I'm going about it wrong then what's the way to add that class?
  • Kevin B
    Kevin B almost 12 years
    Do you know what is creating those images?
  • Kevin B
    Kevin B almost 12 years
    It would be best to try to add the class to the images after whatever script is creating the images is done creating them.
  • BozoExplosion
    BozoExplosion almost 12 years
    Yeah, that's pretty much where I'm headed. From the other comments though it appears I'm running into trouble because, strictly speaking, the images either A)aren't visible when the page loads, and so the query for images fails to find any ~ OR ~ B) the script is loading on the page before the images load (whether visible or not) and so the query fails. I'm not sure if it's one of those, both of those, or something else. I need these images to not be visible when the page loads, but to hit 'em with the class anyway.
  • BozoExplosion
    BozoExplosion almost 12 years
    I've seen this a couple of ways: $("img[src*=menumain-]").attr({class:"menumain"}); ~ and also ~ $("img[src*=menumain-]").attr("class","menumain"); I'm not sure if one is wrong, or if they're both usable, but one better than the other for some reason.
  • BozoExplosion
    BozoExplosion almost 12 years
    There is a javascript that I believe is creating the images: if (is.min) {document.write(image194.div); etc. etc.}. After that the Divs are there with their images inside them, then some more stuff, eventually my script attempting to add the class to those Divs (in the current version of this attempt). All of that, BTW, visible in the HTML tab of Firebug (testing this off of my desktop). So if the images are on the page, and then my script shows up lower in the HTML, I would think the images are "available" to be changed. No?
  • BozoExplosion
    BozoExplosion almost 12 years
    So I guess the question is "Am I building the selector incorrectly (or inappropriately) or is it that the selector is fine, but that some other aspect of HTML (such as 'the images are hidden' or 'the images don't exist' or 'the images are down inside their own Divs') is preventing it from working as I intend it to?"
  • Kevin B
    Kevin B almost 12 years
    The problem is the images don't exist at domready. you need to wait until after the other script is done creating them. I haven't had time to really look at it, but i'm pretty sure that the script that is building the images has a finish callback of some sort.
  • Jeff Fabiny
    Jeff Fabiny almost 12 years
    @BozoExplosion Can you try adding the class after the images are called? That is, whatever event handler is 'showing' the images, have it use a callback function to add the class. It will happen fast enough that the user won't notice it.