views:

360

answers:

3

I have an image map in my page:

<div id="books">
  <img src="images/books.png" width="330" height="298" border="0" \
   usemap="#map_books" />
  <map name="map_books" id="map_books" alt="books">
    <area shape="poly" coords="17,73,81,288,210,248,254,264, ..." \ 
     href="/about" alt="books" />
  </map>
</div>

I have a function that tries to find the image in the document using this map:

function(elemId) { // elemId = "#map_books"

  if ($(elemId).attr("tagName") == "MAP") {
    // find image using this map
    var selector = "img [usemap=\\" + elemId + "]"; 
    var img = $(selector);

    if (img.length == 0) {
      console.log("Could not find image using " + selector);
    }
}

It fails to find the image.

Could not find image using img [usemap=\#map_books]

I've escaped the elemId because it starts with a hash and tried variations of selectors.

$("img [usemap$=" + elemId.substring(1) + "]")
$("img").find("[usemap=\\" + elemId + "]")

Neither find the image. Any ideas?

+1  A: 

Try variations on quoting the usemap value:

$("img[usemap='#whatever']");
$('img[usemap="#whatever"]');
John Fisher
It doesn't have anything to do with quoting. Per the docs: http://api.jquery.com/category/selectors/ his escaping of the hash is correct and, per the docs for that specific selector: http://api.jquery.com/attribute-equals-selector quotes are entirely optional
Dancrumb
Since this works too, I'll give you an up vote but I'm awarding this to Dancrumb.
Greg K
This works because @John removed your rogue space as well as adding the quotes
Dancrumb
Yup, I realise that now you've explained it. Thanks
Greg K
+1  A: 

You have a space between img and [usemap=\#map_books].

That results in an attempt to match a child element of img with an attribute usemap set to #map_books.

You should use:

var selector = "img[usemap=\\" + elemId + "]"; 
Dancrumb
Doh, thought it would be something trivial, thanks!
Greg K
A: 
function(elemId) { // elemId = "#map_books"

    if ($('map'+elemId).length) {
        // find image using this map
        var selector = "img[usemap=\\" + elemId + "]"; 
        var img = $(selector);

        if (img.length == 0) {
            console.log("Could not find image using " + selector);
        }
    }
}

You had an extra space between img and [] for getting to the img's attributes.

PetersenDidIt
Thanks, you were just a few mins behind others providing a correct answer.
Greg K