Not able to get or find element by data attribute using jquery


Hi, i am using the below jQuery code to find element using it's data-attribute in jQuery but i am not able to get it, here is my HTML Code

<h4 class="panel-title">
<a class="accordion-toggle accordion-toggle-styled collapsed" data-toggle="collapse" href="#Test-22496" aria-expanded="false">
  Test(s)
 <i class="fa fa-plus-circle GetTest" data-id="22496" style="cursor:pointer"></i>
 (<span class="TestNumbers">7</span>)
</a>
</h4>

<h4 class="panel-title">
<a class="accordion-toggle accordion-toggle-styled collapsed" data-toggle="collapse" href="#Test-22497" aria-expanded="false">
  Test(s)
 <i class="fa fa-plus-circle GetTest" data-id="22497" style="cursor:pointer"></i>
 (<span class="TestNumbers">7</span>)
</a>
</h4>

<h4 class="panel-title">
<a class="accordion-toggle accordion-toggle-styled collapsed" data-toggle="collapse" href="#Test-22498" aria-expanded="false">
  Test(s)
 <i class="fa fa-plus-circle GetTest" data-id="22498" style="cursor:pointer"></i>
 (<span class="TestNumbers">7</span>)
</a>
</h4>

and here is my current jQuery code to get <i> element of class .GetTest with data-id="22498"

var id='22498';
$('.GetQuote[data-id="' + id + '"]').closest('span').html('New HTML');

Is this correct way or am i missing something ?any help is appreciated


Asked by:- pika
0
: 2941 At:- 12/18/2017 11:46:11 AM
jQuery select-element-by-data-attribute







1 Answers
profileImage Answered by:- Vipin

Your code to get element using attribute in jQuery looks fine to me

$('.GetQuote[data-id="' + id + '"]').closest('span').html('New HTML');

But please check if there is any <span> closest to the elemtn which you need, if it isn't it will throw error and will not work.

Here is the possible way to get element using data atrribute in jquery

1. $(".GetQuote").find("[data-id='" + current_id_value + "']");

2. $(".GetQuote[data-id='" + current_id_value +"']");
1
At:- 12/20/2017 7:08:56 AM
thanks, I saw the issue was as you have mentioned, there wasn't any .closest() element , because of which code was throwing error, now it works :) 0
By : pika - at :- 12/23/2017 2:16:26 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use