I have an element that has a my custom attribute on a <button class="navbar-toggle">
element called data-toggle-wmc
and I am trying to check whether the attribute value equals a string value called collapse
somehow it has not worked so far.
I tried the following
if ($('button.navbar-toggle').attr('data-toggle-wmc') === 'collapse') {
alert('123yes');
}
I also tried
if ($('button.navbar-toggle').attr('data-toggle-wmc') == 'collapse') {
alert('123yes');
}
I looked at this question but somehow the condition is not being fullfilled.
I have an element that has a my custom attribute on a <button class="navbar-toggle">
element called data-toggle-wmc
and I am trying to check whether the attribute value equals a string value called collapse
somehow it has not worked so far.
I tried the following
if ($('button.navbar-toggle').attr('data-toggle-wmc') === 'collapse') {
alert('123yes');
}
I also tried
if ($('button.navbar-toggle').attr('data-toggle-wmc') == 'collapse') {
alert('123yes');
}
I looked at this question but somehow the condition is not being fullfilled.
Share Improve this question edited Oct 20, 2017 at 12:24 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Oct 20, 2017 at 12:20 ShanjayGShanjayG 1,0234 gold badges19 silver badges35 bronze badges 7-
1
You're missing a
'
-.attr('data-toggle-wmc')
. Also, usedata('toggle-wmc') == 'collpase'
instead – Rory McCrossan Commented Oct 20, 2017 at 12:20 -
1
I don't know if its a typo but you are missing a ` ' ` after
data-toggle-wmc)
– VTodorov Commented Oct 20, 2017 at 12:21 - It is only a typo on this question, but not on my actual code. – ShanjayG Commented Oct 20, 2017 at 12:23
-
Do you have only one element for selector
button.navbar-toggle
? – Satpal Commented Oct 20, 2017 at 12:25 -
In which case your code works fine: jsfiddle/f53o5dwL. This means either you have multiple
button.navbar-toggle
elements, the element doesn't have the attribute - hence my suggestion above to usedata()
as it may be added to jQuery's cache, not the DOM, or there is an error elsewhere in your code and you need to check the console to see it. In any of the above cases we need to see more of your HTML and JS code in order to help you effectively. – Rory McCrossan Commented Oct 20, 2017 at 12:26
3 Answers
Reset to default 3Try:
if ($('button.navbar-toggle').data('toggle-wmc') === 'collapse') ...
Access data properties with $.data. it seems to work like this
$("button.navbar-toggle").on("click", function(){
if($(this).data("toggle-wmc") === "collapse"){
console.log($(this).data("toggle-wmc"));
}
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="navbar-toggle" data-toggle-wmc="collapse" width="100" height="50">button</button>
There was an argument error in your code. Try this
if ($('button.navbar-toggle').attr('data-toggle-wmc') == 'collapse') {
alert('123yes');
}