刚入职的时候看到公司用的HTML日志生成工具附带的Panel,工具不够用,找个Fail还要找半天,于是自己琢磨着添砖加瓦。以前也是个半吊子前端工程师,现在可倒好,想要改页面却连页面生成的模板在哪里都不知道,只有通过改动JavaScript才能实现对页面的修改。

固然,操作DOM有原版的

document.getElementsBy

一族,可是它们get的时候不能通过 class 和 标签 来区分,比如:

<div class="FAIL">
<tr class="FAIL">
<td class="FAIL ">I am row NO.1</td>
<td class="TRACE">I am row NO.2</td>
<td class="DEBUG">I am row NO.3</td>
<td class="ERROR">I am row NO.4</td>
</tr>
</div>

通过Class查找会找出一堆FAIL;通过Tag查找……算了吧;通过ID查找……好吧根本没有定义过ID。

活人总不能被尿憋死,CSS3中增强了对选择器的支持,新特性中有:

document.querySelector

函数家族,他们是:

document.querySelector('tagName.className') 

An Element object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.(By MDN)

返回匹配输入的CSS选择器的第一个元素,如果没有匹配的元素,返回空(null)。

document.querySelectorAll('tagName.className') 

If you need a list of all elements matching the specified selectors, you should use querySelectorAll() instead.(By MDN)

如果你需要找到所有的匹配元素,请使用querySelectorAll

真的是很方便了。实际案例在下面!

还值得一提的是,这个方法相比于Anchor,多了方便的动画和滚动位置设定

document.querySelectorAll(eventName)[index].scrollIntoView({ behavior:"auto, "block: "start", inline: "nearest" });

三个属性分别控制动画、滚动到所选区域的哪里,滚动到本页面的哪里。比起 “herf="#top"”来讲方便了许多啊!

部分案例代码:

 /*
Function to add some new buttons to the panel Input: *None* Returns: *None* Effects: add "to top", "to bottom", "find fail" and "find error" buttons Modified on Mar 2019 by Jack Lyu Advise / Next stage: remove functions and put these buttons inside the HTML pages
*/ function addButtons() {
//adding anchor to page
var pageTop = document.createElement('a');
pageTop.setAttribute("id", "top");
var pageBottom = document.createElement('a');
pageBottom.setAttribute("id", "bottom")
var tableBody = document.getElementById("content");
tableBody.insertBefore(pageTop, tableBody.firstChild);
$(pageBottom).insertAfter(tableBody); //adding link to page
var infoText = document.createElement('p');
infoText.setAttribute("style", "font-size: 1em;margin:0 0 5px 5px");
infoText.innerHTML = "Navigator v1.0<br><div style='color:red;>'>Error(s):" + window.counterError + " Fail(s):" + window.counterFail + "</div>";
var toTop = document.createElement('a');
toTop.setAttribute("href", "#top");
toTop.setAttribute("onclick", "resetCounter('All')");
toTop.setAttribute("style", "color:#333333;margin:5px 0 0 5px;border:2px solid #6CDFEA;");
toTop.innerHTML = "To Top";

// 省略一部分 panleBottom.insertBefore(toBottom, panleBottom.lastChild); //adding "find next fail" button function
var failButton = document.createElement('div');
failButton.setAttribute("style", "margin: 15px 0 0 5px;");
var findNextFail = document.createElement('a');
findNextFail.setAttribute("href", "javascript:void(233)");
findNextFail.setAttribute("onclick", "findNext('tr.FAIL')");
findNextFail.setAttribute("style", "color:#333333;border:3px solid #F02311;margin-left:5px;padding:5px 1.19em 5px 5px;width:30%;text-align:center");
findNextFail.innerHTML = "Next FAIL";
failButton.insertBefore(findNextFail, failButton.lastChild);
//adding "Prev fail" button function
var findFail = document.createElement('a');
findFail.setAttribute("href", "javascript:void(233)");
findFail.setAttribute("onclick", "findNext('tr.FAIL',false)");
findFail.setAttribute("style", "color:#333333;border:3px solid #F02311;padding:5px 1.19em 5px 5px;width:30%;text-align:center");
findFail.innerHTML = "Prev FAIL";
failButton.insertBefore(findFail, failButton.lastChild);

// 省略一部分

//add both button to panle
panleBottom.insertBefore(errorButton, panleBottom.lastChild);
} /*
Function to locate target event Input: eventName Returns: *None*
*/ function findEvent(eventName) {
var list = document.querySelectorAll(eventName);
var tag = eventName.split(".")[1];
for (let index = list.length - 1; index >= 0; index--) {
list[index].setAttribute("id", tag + index);
list[index].firstChild.setAttribute("style", "background-color:#FFC943")
}
} /*
Function to find next event Input: eventName Returns: *None* Notice: Only work on some browsers: Chorme 29 and above(animation work on 61 above), IE8 and above, Firefox 1 and above(animation work on 36 above)
*/ function findNext(eventName, isNext) {
var index;
if (isNext == false) {
addCounter(eventName, 2);
findNext(eventName);
return;
}
else if (eventName == 'tr.ERROR') {
if (pointerError < 1) { resetCounter('tr.ERROR'); }
index = counterError - pointerError;
pointerError--;
}
else if (eventName == 'tr.FAIL') {
if (pointerFail < 1) { resetCounter('tr.FAIL'); }
index = counterFail - pointerFail;
pointerFail--;
} else { alert('Script findNext error, call maintainer for help.'); }
document.querySelectorAll(eventName)[index].scrollIntoView({ block: "start", inline: "nearest" });
}

[2019.03.16]使用DOM操作函数和CSS选择器来针对已有的HTML进行只凭JS的改动的更多相关文章

  1. JS DOM操作 函数 事件 阻止事件冒泡

    一 函数 1.字符串函数 s.tolowerCase( ):    -- 变小写 s.toupperCase( ):   -- 变大写 s.substr( 2 , 8 ):     -- 截取     ...

  2. 2019.03.16 ZJOI2019模拟赛 解题报告

    得分: \(100+27+20=147\)(\(T1\)巨水,\(T2,T3\)只能写暴力分) \(T1\):深邃 比较套路的一眼题,显然是一个二分+贪心,感觉就是\(NOIP2018Day1T3\) ...

  3. jQuery-1.9.1源码分析系列(十一) DOM操作

    DOM操作包括append.prepend.before.after.replaceWith.appendTo.prependTo.insertBefore.insertAfter.replaceAl ...

  4. 【summary】JQuery 相关css、ajax、数据操作函数或方法

    总结一下JQuery常用的函数方法,更加系统的整理一下. JQuery遍历的一些函数: 函数 描述 .add() 将元素添加到匹配元素的集合中. .andSelf() 把堆栈中之前的元素集添加到当前集 ...

  5. 原生JavaScript常用的DOM操作

    之前项目一直都是用JQuery或者Vue来做的,确实好用,毕竟帮我们解决了很多浏览器兼容问题,但是后面发现大公司面试题都是要原生Javascript来做,然后我就一脸懵逼哈哈哈,毕竟大公司需要的框架或 ...

  6. React.js 小书 Lesson21 - ref 和 React.js 中的 DOM 操作

    作者:胡子大哈 原文链接:http://huziketang.com/books/react/lesson21 转载请注明出处,保留原文链接和作者信息. 在 React.js 当中你基本不需要和 DO ...

  7. ref 和 React.js 中的 DOM 操作

    在 React.js 当中你基本不需要和 DOM 直接打交道.React.js 提供了一系列的 on*方法帮助我们进行事件监听,所以 React.js 当中不需要直接调用 addEventListen ...

  8. javascrtpt DOM操作

    DOM DOM:(document object mode)文档对象模型.DOM为文档提供了结构化表示,并定义了如何通过脚本来访问文档结构. 目的就是为了能让js操作html元素而制定的一个规范 DO ...

  9. 解密jQuery内核 DOM操作的核心函数domManip

    domManip是什么 dom即Dom元素,Manip是Manipulate的缩写,连在一起就是Dom操作的意思. .domManip()是jQuery DOM操作的核心函数 对封装的节点操作做了参数 ...

随机推荐

  1. Reactive Extensions 相见恨晚的Rx.Net

    何为Reactive Extensions(Rx) Rx是一个遵循函数式编程的类库,它引用观察者以及迭代器设计模式对可观察对象产生的数据进行异步消费.使用Rx, 开发人员将使用LINQ运算符操作异步数 ...

  2. 引用KBC.PetroSIM.Interop的dll,在代码中调用时出现 80040154 没有注册类 的错误

    失败的尝试: regsvr32注册:模块已加载,但找不到入口点DllRegisterServer regasm注册:需写上regasm的完整路径,注册成功,但问题依旧 将项目的平台改为x86:问题依旧 ...

  3. ASP.NET Core 基于JWT的认证(一)

    ASP.NET Core 基于JWT的认证(一) Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计 ...

  4. Python3中列表字符串转数字

    比如我们有个列表: number = [']; 如果我们需要将列表里的元素转换为数字呢?最常用的大家可能会想到使用列表推导式: number = ['] number = [int(x) for x ...

  5. 设计模式系列6:适配器模式(Adapter Pattern)

    定义 将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作.    --<设计模式>GoF UML类图 使用场景 在遗留代码复用,类 ...

  6. Django之路由分发和反向解析

    一.路由分发: 路由分发是指:总路由不再直接做路由与视图函数的对应关系,而是将获取的路由分发给下面的app去处理对应关系 from django.conf.urls import url,includ ...

  7. 解决PostGIS打开shp文件输入输出模块出现"找不到文件libintl-9.dll"的问题

    找到shp2pgsql-gui.exe这个程序的目录 复制一份libintl-8.dll副本,改名为libintl-9.dll即可.

  8. nlp词性标注

    nlp词性标注 与分词函数不同,jieba库和pyltp库词性标注函数上形式相差极大. jieba的词性标注函数与分词函数相近,jieba.posseg.cut(sentence,HMM=True)函 ...

  9. Android 沉浸式状态栏完美解决方案

    现在搜索Android 沉浸式状态栏,真的是一堆一堆,写的特别多,但是真正用的舒服的真没有,在这里自己整理一下开发记录 注意,在使用这个步骤过程之前,请把之前设置的代码注释一下 把布局带有androi ...

  10. lambda 怎么传递ref参数

    lambda 传递ref参数有个语法bug,必须要显式书写参数类型. //如 delegate bool FuncType(ref int num); FuncType func1; func1 = ...