Simple Implementation of Obtaining class in javascript
- 2021-07-02 23:21:34
- OfStack
There is no way to get class in js, and I have found some encapsulated methods, so I will sort them out here
(1) Package first
// Encapsulation getClass
function getClass(tagName,className) // Get the label name tagName, Class name className Elements of
{
if(document.getElementsByClassName) // Support this function
{ return document.getElementsByClassName(className);
}
else
{ var tags=document.getElementsByTagName(tagName);// Get Label
var tagArr=[];// Used to return a class named className Elements of
for(var i=0;i < tags.length; i++)
{
if(tags[i].class == className)
{
tagArr[tagArr.length] = tags[i];// Save the elements that meet the conditions
}
}
return tagArr;
}
}
(2) Subject program
<ul>
<li class="dicTap">1</li>
<li class="dicTap">2</li>
<li class="dicTap">3</li>
<li class="dicTap">4</li>
</ul>
(3) Obtain all li content programs whose class is dicTap
window.onload = function()
{ var topMenus = getClass('li','dicTap');
for(var i=0;i < topMenus.length; i++)
{
alert(topMenus[i].innerHTML);
}
}
(4) Practical application in the project
// Clicked Custom properties personid Open the Details page and cross-page value transfer
var dicTap = getClass('li','dicTap');
for(var i=0;i <dicTap.length; i++)
{
dicTap[i].addEventListener('tap',function(){
var personId=this.getAttribute("personid");
localStorage.a=personId;
mui.openWindow({
url: 'disciplineDetail.html',
id:'disciplineDetail'
});
})
}
// Encapsulation getClass
function getClass(tagName,className) // Get the label name tagName, Class name className Elements of
{
if(document.getElementsByClassName) // Support this function
{ return document.getElementsByClassName(className);
}
else
{ var tags=document.getElementsByTagName(tagName);// Get Label
var tagArr=[];// Used to return a class named className Elements of
for(var i=0;i < tags.length; i++)
{
if(tags[i].class == className)
{
tagArr[tagArr.length] = tags[i];// Save the elements that meet the conditions
}
}
return tagArr;
}
}