Reputation: 5967
Following are class names
<p class="question3.1">Question 3.1</p>
<p class="question3.10">Question 3.10</p>
<p class="question3.11">Question 3.11</p>
<p class="question3.12">Question 3.12</p>
I want to get value of text 3.1 in JQuery:
alert($("p[class*='question3.1']").text())
It returns text of all questions i.e
Question 3.1Question 3.10Question 3.11Question 3.12
But if i use following then it work fine.
alert($("p[class*='question3.10']").text())
How can i pick text of question3.1 only?
I could not refactor HTML.
Fiddle: https://jsfiddle.net/e9w9fhyw/
Upvotes: 0
Views: 498
Reputation: 1074178
Those classnames are insane.
You can select them, though. You have two choices:
A class selector that you escape the .
in, and
The whitespace-separated attribute selector (~=
)
The CSS class selector for the first one is
.question3\2e\31
\2e
is the dot, and then because it happens that what follows the dot is a digit, which could be taken into the escape sequence, we use \31
for the 1
.
To write that in a jQuery selector you have to escape the backslashes, so to get the first one, you'd use:
$(".question3\\2e\\31").text()
Live Example:
document.body.insertAdjacentHTML(
"beforeend",
"The first one is: " + $(".question3\\2e\\31").text()
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="question3.1">Question 3.1</p>
<p class="question3.10">Question 3.10</p>
<p class="question3.11">Question 3.11</p>
<p class="question3.12">Question 3.12</p>
<hr>
The whitespace-separated attribute selector [att~="val"]
...
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.
So:
$('[class~="question3.1"]').text()
Live Example:
document.body.insertAdjacentHTML(
"beforeend",
"The first one is: " + $('[class~="question3.1"]').text()
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="question3.1">Question 3.1</p>
<p class="question3.10">Question 3.10</p>
<p class="question3.11">Question 3.11</p>
<p class="question3.12">Question 3.12</p>
<hr>
Upvotes: 4
Reputation: 1506
I would suggest you to have a look at: Link. So change it to something like this:
<p class="question" data-question="3.1">Question 3.1</p>
<p class="question" data-question="3.10">Question 3.10</p>
<p class="question" data-question="3.11">Question 3.11</p>
<p class="question" data-question="3.12">Question 3.12</p>
And then your jQuery would be:
$(document).ready(function(){
console.log($('.question[data-question="3.10"]').html());
});
The above will print Question 3.10 in your console!
Upvotes: -1