keith.quiche keith.quiche - 6 months ago 17
Javascript Question

Syntax error, unrecognized expression: ' .d img.displayImage'

This is my HTML:

<div class="flex-item a">
<p>A</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>

<div class="flex-item b">
<p>B</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>

<div class="flex-item c">
<p>C</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>

<div class="flex-item d">
<p>D</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>


This is my js:

var arr = ["a", "b", "c", "d"];
var imageAreaArray = [];

$.each(arr, function(i, val){
imageAreaArray.push("document.querySelector('." + val + " img.displayImage')");
});

$.each(imageAreaArray, function(i, val){
var contentVal = $("'." + arr[i] + "img.displayImage'").closest('textarea');
imagePath = $("'." + arr[i] + " img.displayImage'").src;
});


This should take the value of the nearest
<textarea>
to the
img.displayImage
in the selected '
<div>
', and also take the
src
of the
img.displayImage
, but I get the following error and I'm not sure how to fix.


Uncaught Error: Syntax error, unrecognized expression: '.d img.displayImage'


UPDATE

No longer getting the error message, but now
contentVal
and
imagePath
are showing as undefined. Any idea why undefined might be showing?

Answer

I see two potential problems with your code. First off, I don't believe that jQuery selectors need to be wrapped in single quotes, so get rid of those. Secondly, when querying for the closest textarea you missed a space between arr[i] and img.displayImage.

I would suggest caching the jQuery selected element:

var element = $(`.${arr[i]} img.displayImage`);
var contentVal = element.closest('textarea');
imagePath = element.src;

Notice that the ` characters are backticks, typically found at the top-left of English keyboards. This syntax requires that ES6 string interpolation is supported by the browsers you're targeting. As an alternative, you can just build the selector by using the same method you're currently employing.

var element = $("'." + arr[i] + " img.displayImage'");
...