zoukankan      html  css  js  c++  java
  • 使用原生JavaScript模拟getElementByClassName .

    最近在工作中,由于有一个插件必须使用jquery-pack.js,而这个包又是非常古老的jquery,所以又的函数是无法使用的,例如$()选择器以及parent()都取不到标签的内容。

    所以没办法,只能用原生的JavaScript了,为了实现这个功能,我得通过HTML标签的Class来获得标签的DOM结构。

    在JavaScript 内建的核心中,document对象及element对象总共可以通过三个方式来获取其下的元素,分别是:getElementById(‘id’) 、getElementsByName(‘name’) 、getElementsByTagName(‘tag’)  。

    可是在设计网页时,最常常需要使用到的class却没有相对应的方法可以去获取className相同的元素。

    不过我们可以自己写一个,代码以很简单:

    function getElementsByClassName(tagName,className) {
            var tag = document.getElementsByTagName(tagName);
            var tagAll = [];
            for(var i = 0 ; i<tag.length ; i++){
                if(tag[i].className.indexOf(className) != -1){
                    tagAll[tagAll.length] = tag[i];
                }
            }
    
            return tagAll;
    
        }
    


    原理就是通过获取指定的标签,使用getElementsByTagName来获取标签的内容,然后根据标签的className跟传进来的参数进行对比,如果相等就放入数组中最后返回。

  • 相关阅读:
    (HDU)1097 --A hard puzzle(难题)
    (HDU)1096 --A+B for Input-Output Practice (VIII)(输入输出练习(VIII))
    PAT B1008——数组元素循环右移
    test
    vue iconfont矢量图
    css3简单旋转
    vue 路由的安装及使用
    vue 父组件与子组件之间的相互调用
    vue 脚手架安装
    PHP 加密方式
  • 原文地址:https://www.cnblogs.com/firstdream/p/5530662.html
Copyright © 2011-2022 走看看