Adrian Ani Adrian Ani - 5 months ago 23
Javascript Question

Change element css if a custom attribute has a specific value jquery

Why the css applies to all the elements with that class even with that if statement ?
Is something wrong?


if( $( '.simply-drop-menu' ).attr( 'data-type-simply-menu' ) == 'user_friends-request' ) {
$( '.simply-drop-menu' ).css({
'top': '130px',
'right': '21px',
'opacity': '0',
'pointer-events': 'none'
});
}

Answer

If the if-statement evaluates as true, the selector that is being used .simply-drop-down will target all elements with that class and apply the appropriate properties to them :

// This will target every element with the class 'simply-drop-down'
$('.simply-drop-menu').css({
        'top': '130px',
        'right': '21px',
        'opacity': '0',
        'pointer-events': 'none'
});

Consider an Attribute Selector

Instead you might want to consider using the attribute equals selector to only target those elements with that specific attribute value :

// This will target all elements with the class 'simply-drop-down' that have a data 
// attribute of 'data-type-simply-menu' with a value of 'user_friends-request'
$('.simply-drop-menu[data-type-simply-menu="user_friends-request"]').css({
        'top': '130px',
        'right': '21px',
        'opacity': '0',
        'pointer-events': 'none'
});

This also eliminates the need for an if-statement to be used as well.

Example

enter image description here

// This will only target your drop down elements with the proper attribute value
$('.simply-drop-menu[data-type-simply-menu="user_friends-request"]').css({
  'color': 'red'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>Notice only the simply-drop-down class with the appropriate data attribute is red.</pre>
<div class='simply-drop-menu' data-type-simply-menu="user_friends-request">class='simply-drop-menu' data-type-simply-menu="user_friends-request"</div>
<div class='simply-drop-menu'>class='simply-drop-menu'</div>
<div data-type-simply-menu="user_friends-request">data-type-simply-menu="user_friends-request"</div>
<div class='simply-drop-menu' data-type-simply-menu="user_friends-foo">class='simply-drop-menu' data-type-simply-menu="user_friends-foo"</div>