retrieving element with specific value of data attribute in jquery


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 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;">    

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 = $'name')=="myCar".css('left');
but I think the syntax is wrong; how do I select it please?


I think it should be:

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

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


This worked for me:

<!DOCTYPE html>
<html lang="en">
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <a href="#">
            <img src="hacker.png" data-name="myCar" />
        <a href="#">
            <img src="hacker.png" data-name="yourCar" />
        <script type="text/javascript" src=""></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() });

should work


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 2 Years Ago by pritaeas and jstfsklh211
This question has already been solved: Start a new discussion instead
Start New Discussion
Tags Related to this Article