简体   繁体   中英

How do you only select the second class an element has in javascript?

I am in need of a way to select only the second class on an element that has 2 classes so that I can pass it through an URL to use later. I have created a function that gets both classes but I only need class2 . Is their a way to stripe the first class off and have only the second remain. Or is their a way to select only the second class.

I did not find any questions relating to this problem using just vanilla javascript.

<div class="class1 class2></div>
<script>

function get2ndClass(element) {

   var secondClass = element.class;
   return secondClass;

}

Use the classList array property to first of all check whether there are at least 2 classes, then return the 2nd item in the array.

function get2ndClass(element) {
   return (element && element.classList.length>1) ? element.classList[1] : null;
}

If you're supporting older browsers which don't support classList then you'll need an additional line:

function get2ndClass(element) {
   var classList = (element) ? element.className.split(" ") : null;
   return (classList && element.classList.length>1) ? element.classList[1] : null;
}

您可以使用classList获取分配给元素的类

return element.classList.length > 1 ? element.classList[1] : "";

No need for classList support, just split the element class attributes:

 function get2ndClass(elt) { return elt.getAttribute('class').split(' ')[1] || null; } console.log(get2ndClass(document.getElementsByTagName('div')[0])) 
 <div class="class1 class2" > 

使用拆分

 console.log("class1 class2".split(" ").pop()); 

Use classList

 function get2ndClass(element) { return element.classList[1] || false; } var $div = document.querySelector('div') var secondClass = get2ndClass($div); console.log(secondClass); 
 <div class="firstClass secondClass"></div> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM