Nath CoLLN
Nath CoLLN

Reputation: 3

How to escape double-quote in jQuery

I don't succeed in escaping a double-quote (") in jQuery.

Here is my code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
.red { border-top: 10px solid red; }
.yellow { border-top: 10px solid yellow; }
.left { border-left: 3px solid green; } 
</style>
</head>
<body>
<ul id="choose">
    <li>Goofy</li>
  <li><a href="blabla.aspx">Mickey</a></li>
  <li><a href="other.ext">Mickey</a></li>
  <li>Pluto</li>
</ul>
    
<script>
$(document).ready(function(){
  $("p:contains(is)").css("background-color", "yellow");
  $("li:contains('Mickey')").addClass('left');
  $("li:contains('aspx">Mickey')").addClass('yellow');
  $("li:contains('Pluto')").addClass('left');
});
</script>

</body>
</html>

Upvotes: 0

Views: 77

Answers (1)

TiiJ7
TiiJ7

Reputation: 3412

It's not really a good idea to try to find a piece of literal HTML code with contains. HTML tends to change, and even a single space could break the code.

Instead, use :has and pass a proper selector for the child:

$(document).ready(function(){
  $("p:contains(is)").css("background-color", "yellow");
  $("li:contains('Mickey')").addClass('left');
  $("li:has(a[href$=aspx]:contains('Mickey'))").addClass("yellow");
  $("li:contains('Pluto')").addClass('left');
});
.red { border-top: 10px solid red; }
.yellow { border-top: 10px solid yellow; }
.left { border-left: 3px solid green; } 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<ul id="choose">
  <li>Goofy</li>
  <li><a href="blabla.aspx">Mickey</a></li>
  <li><a href="other.ext">Mickey</a></li>
  <li>Pluto</li>
</ul>

Alternatively, you can also use just the selector of the link itself and get the li with .parent().

Upvotes: 2

Related Questions