The problem is that jQuery returns undefined
and I have no clue why…
The following runs with latest WordPress and Woocommerce. jQuery used is the WP default.
I have the following html (just a fragment for readability) and the button is hidden at first and revealed later.
Much below and activated by the user click on the "click me" button above to activate the following js:
(function($) {
$(document).on('click', '#llwoo-update-profile-field-button', function() {
// $('#llwoo-update-profile-field-button').live('click', function() {
let t = $('.ll-li-tabs .ui-state-active'); // returns OK
console.log("Handler for .click() called. t=", t);
let t2 = $('.ll-li-tabs .ui-state-active').attr('aria-controls'); // return undefined!
console.log("Handler for .click() called. t2=", t2);
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<ul>
<li class="ll-li-tabs ui-tabs-tab ui-corner-top ui-state-default ui-tab ui-tabs-active ui-state-active" role="tab" tabindex="0" aria-controls="tabs-2" aria-labelledby="ui-id-2" aria-selected="true" aria-expanded="true">
<a href="#tabs-2" role="presentation" tabindex="-1" class="ui-tabs-anchor" id="ui-id-2">
<div id="ll-box-TR" class="ll-box-s ll-box-TR">li with aria-controls</div>
</a>
</li>
</ul>
<div id="llwoo-update-profile-field" class="llwoo-update-profile-field">
<button id="llwoo-update-profile-field-button" type="button">click me</button></div>
t
has a value while t2
is undefined and ‘aria-controls’ exists.
Any idea where the problem is? What am I missing?
EDIT: I replace live
with on
– Same problem remains…
Thanks!
3
Answers
jquery doesn’t support
live()
. Useon()
.I guess you are getting multiple
objects
for$('.ll-li-tabs .ui-state-active')
. Andattr
will select first of them and return the value.Please note that you are having
like
ll-li-tabs
&ui-state-active
both classes onli
so you should be using them without$('.ll-li-tabs.ui-state-active')
.If you want to get
$('.ll-li-tabs.ui-state-active')
with specificattribute
you can useattribute selector
[]
. In your case you can use like below.$('.ll-li-tabs.ui-state-active[aria-controls]')
In below example I’ve set first
li
withoutaria-controls
attribute
and secondli
witharia-controls
. Please check result for$('.ll-li-tabs.ui-state-active').attr('aria-controls');
&$('.ll-li-tabs.ui-state-active[aria-controls]').attr('aria-controls');
if you want to match div that contains just both classes you shouldn’t add space between them in jquery selector
must be
i prefer to use id rather than class for something like this to avoid the problems or use class used one time and put it to selector without any other class.