JQuery: searching for an element with a class name stored in a variable

(Edited in more detail just in case anyone has a similar question)

I have an image map that should show a div when capsizing a hotspot. I have provided my areas in image map classes, and using jQuery I want to show its corresponding div, for example,

area shape="rect" coords="601,31,723,107" href="#" alt="Some Location" class="some-location"

Each area has a different location and therefore a different class name.

I'm not sure how to refer to an element with its class name stored in a variable? For example, the code I currently need to get the class name to hover over an area on the image map:

var hotspot = $(this).attr("class");

Now I want to do something like:

$(div.hotspot).show();

The above does not work - can someone point me in the right direction?

+4
source share
4 answers

Use string concatenation:

 $("div." + hotspot) 

Obviously, this only works if the hotspot contains only class one (see Reigel's comment). If it contains more classes, you should replace the white spaces with a dot:

 $("div." + hotspot.replace(' ', '.')) 

(assuming a few spaces between class names are automatically trimmed, but I'm not sure about it, otherwise you should use the regular expression /\s+/ )

+4
source
 $('.' + hotspot).show(); 

since your hotspot variable contains a class string, you need to pass it as a string selector .

In any case, it does not make much sense , since you will get access to the same element from which you got this class name. If you already queried this element once, you can (and should!) Save / cache the jQuery object in the variable and access it again.

+3
source
 $("#divid").find(hotspot); 

You can use this.

0
source

You need to pass the string argument $() you missed the quotes in your example. you need to do $('.hotspot').show() You can also have var c = '.hotspot';$(c).show()

0
source

Source: https://habr.com/ru/post/1314806/


All Articles