javascripthtmljqueryjquery-selectors

How can I select an HTML element using jQuery where the attribute value contains spaces?


I need to select an HTML element using jQuery where the attribute value contains spaces. For example, I have an attribute data-compare which receives dynamic values from an API. Sometimes the data-compare value contains spaces, such as 'test test test'.

Here is the code I'm using:

$(`#compare_modal_table td[data-compare=${item}]`)

However, this doesn't work because the value contains spaces, resulting in a syntax error in the console log.

How can I correctly select the element when the attribute value has spaces?


Solution

  • Just make this :

    $('#compare_modal_table td[data-compare="' + ${item} + '"]')