I am trying to check a condition where if a link contain " current
" class then I need to perform some action. Links have a custom attribute " data-step"
.
I need to perform some action when data-step="3"
will contain a class current.
The links are here:
<a href="#" data-step="1" class="multistep_section">login</a>
<a href="#" data-step="2" class="multistep_section">billing address</a>
<a href="#" data-step="3" class="current multistep_section">Shipping Address</a>
<a href="#" data-step="4" class="multistep_section">payment</a>
<a href="#" data-step="5" class="multistep_section">order review</a>
class current is variable and changed as per the steps. I need to do some action in jquery or javascript only when data-step="3"
contains class "current"
Any suggestion are welcome
Edited response based on posters feedback:
$(document).ready(function(){
if ($('a[data-step=3]').hasClass('current')){
// Current class exists on data-step 3
}
});
and with plain JS:
(function(){
var elements = document.querySelectorAll('[data-step]');
var targetElement;
for (var i = 0; i < elements.length; i++){
if (elements[i].getAttribute('data-step') == 3){
targetElement = elements[i];
}
}
if (targetElement.classList.contains('current')){
alert("Has current class");
}
})();
See plain JS example: http://jsfiddle.net/19tmab49/4/
document.addEventListener("DOMContentLoaded", function(event) { var links = document.getElementsByTagName("a"); var class_name = "current"; // if element is contained in an array (function) function isInArray(value, array) { return array.indexOf(value) > -1; } for(var i = 0; i < links.length; i++) { var tempLink = links[i]; // represents each links var dataStep_value = tempLink.getAttribute("data-step"); // getting "data-step" value var classes = tempLink.className.split(" "); if (isInArray(class_name, classes)) { // current is in array, do whatever you need to } } });
<a href="#" data-step="1" class="multistep_section">login</a> <a href="#" data-step="2" class="multistep_section">billing address</a> <a href="#" data-step="3" class="current multistep_section">Shipping Address</a> <a href="#" data-step="4" class="multistep_section">payment</a> <a href="#" data-step="5" class="multistep_section">order review</a>
You will not see the result of this function instead of adding an alert in the area I commented. This script check the data-step
attribute, and check another time for the one that are set to "3" if they contain the class "current" (variable class_name
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.