WHY AM I NOT ABLE TO APPEND AN IMAGE ONLY IF CERTAIN CLASSES EXIST?

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
JQuery 
 1259  View(s)
Ratings:
Rate this:
Hi Everyone!

I am trying to use jQuery to append an image tag to a div only if one of three classes exists, but it doesn't seem to be working. It either appends to all 

of the elements or none at all.

Here is the HTML code:

<figure class="donut minus">
    <div class="figure-value"></div>
</figure>
Here is the jQuery:

if ($("figure.donut").hasClass("minus") || $("figure.donut").hasClass("plus") || $("figure.donut").hasClass("plus-minus")) {
        $(".figure-value").append('<img src="../images/schoolProfile/donut-plus-minus.png" />');
    }

Thanks in advance
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Why am I not able to append an image only if certain classes exist?

    Hi Jayden!

    you can try this way

    $("figure.donut")
        .filter(".plus, .minus, .plus-minus")
        .find(".figure-value")
        .append('<img src="../images/schoolProfile/donut-plus-minus.png" />');

    This will find all of the figures with a class of donut and plus, minus or plus-minus and then find the element with a class of figure-value inside them and append the image.

    In answer to the comment below, change the append to create a jQuery object and apply the css to that:

    .append($('<img src="../images/schoolProfile/donut-plus-minus.png" />')
                .css({"top": -100+"px", "left": 0+"px"}));

    I hope it solve your problem

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!