1

I have to select a div element id with escape characters,

HTML

<div id="abc/def"></div>

Tried these,

$("#abc/def").find('h4').attr('data-val', "test")  //didn't work

$("id=[abc/def]").find('h4').attr('data-val', "test")  //didn't work

$("#"+escapeSelector("abc/def")).find('h4').attr('data-val',"Test")   //didn't work

function escapeSelector(s) {
    return s.replace(/(:|\.|\[|\])/g, "\\$1");
}

Error:

Syntax error, unrecognized expression: #abc/def

Where should i make the change to make this work?

1
  • As an option, you may try jQuery("div[id^=abc]") OR jQuery("#abc\\/def") Commented Apr 13, 2017 at 14:29

2 Answers 2

3
$("#abc\\/def").text("test")  //did work :)

https://jsfiddle.net/gtpkkyw0/

There is really good info on the jquery site as well. Leaving here as a reference, hope it helps someone:

https://api.jquery.com/category/selectors/

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, you need to escape a few chars in jquery selector. You need this also for [ ].
2

You don't have to escape anything with the Attribute equals selector :

$('[id="abc/def"]')

https://jsfiddle.net/86uohuny/

Comments

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.