0

I have a div with an attribute of "foldername" which can something like "shoes, "dresses," etc . The div looks like this:

<div id='folder_template' class="openclosed_folder_icon subfolder" foldername="shoes">
    <img class="folder_icon" src="images/folder_closed.png"  />
    <div class="folder_label">name</div> 
</div> 

I want to search for the div that has a particular value for foldername and change the image in it from "folder_closed.png" to "folder_open.png," so the graphic looks like an open folder instead of a closed folder. So I have the code:

$("div[foldername=g.currentGallery]").attr('src','images/folder_open.png'); 

where g.currentGallery is a variable holding the gallery name, e.g., "shoes," that I want to change. But this line gives me the error:

Syntax error, unrecognized expression: div[foldername=g.currentGallery]

But it will take:

$("div[foldername='shoes']").attr('src','images/folder_open.png');

Why can't I use a variable here?

1 Answer 1

1

Like this:

$('div[foldername="' + g.currentGallery.replace(/"/g, '\\"') + '"]').attr(/* whatever */);

Example if we have:

var g = { currentGallery: 'shoes["1"]' };

Then the selector expression becomes:

div[foldername="shoes[\"1\"]"]
Sign up to request clarification or add additional context in comments.

4 Comments

This will allow any char, even ]: ..foldername='" + g.currentGallery + "']... ... See: jsfiddle.net/fiddleyetu/k0976349 @salmanA?
@PeterKA: yes, when ] is present in attribute value then quotes become necessary. Revised the answer.
+1 for quote escaping in the string. Never hurts to always quote anyway. :)
My code doesn't have any quotes to escape so the simplified solution was $('div[foldername="' + g.currentGallery + '"]').find('img').attr('src','images/folder_open.png'); Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.