1.11M Members

retrieving element with specific value of data attribute in jquery

 
0
 

Hi I got in a bit of a muddle here. Basically say you have this html:

...
<a href="javascript:void(0)">
    <img alt="" data-name="myCar" data-family="ferrari" data-type="Fast Family" src="images/ferrari.png" style="left: 193.291px; opacity: 0.5; cursor: default;">    
</a>
<a href="javascript:void(0)">
    <img alt="" data-name="yourCar" data-family="aston" data-type="Fast Family" src="images/aston.png" style="left: 293.291px; opacity: 0.5; cursor: default;">    
</a>
...

In my script, there is a variable$allImages = $("a img"); containing all the images and I want to select exactly the element whose data-name attribute value is myCar and find its position - mind there are many more cars in the list.
So what I have tried first is this:
var theCar = $allImages.attr('[data-name="myCar"]').css('left');
and then
var theCar = $allImages.data('name')=="myCar".css('left');
but I think the syntax is wrong; how do I select it please?
thanks

 
0
 

I think it should be:

$("a img[data-name='myCar']").css('left');
 
0
 

thanks isn't there any way I can make use of that variable $allImages at all? the above line is returning undefined for whatever reason

 
0
 

This worked for me:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <a href="#">
            <img src="hacker.png" data-name="myCar" />
        </a>
        <a href="#">
            <img src="hacker.png" data-name="yourCar" />
        </a>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $("a img[data-name='myCar']").hide();

                // this works too:
                $allImages = $("a img");
                $.each($allImages, function () { $("[data-name='yourCar']").hide() });
            });
        </script>
    </body>
</html>
 
0
 

should work

$allImages.children("[data-name='yourCar']").hide();
 
0
 

thanks guys, it did work eventually, not sure why I was getting undefined, I deleted the code and started again, it all worked thanks for your help as usual

Question Answered as of 1 Year Ago by pritaeas and jstfsklh211
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article