使用香草Javascript查找具有部分属性的DOM元素 [英] Finding DOM element with part of attribute with vanilla Javascript

查看:65
本文介绍了使用香草Javascript查找具有部分属性的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个网站,并且我想使用通过其DOM元素循环的脚本,并指出这些属性包含指定文本的一部分的元素.我设法创建了一个简单的循环,该循环查找DOM元素的每个所需属性并从中创建数组.现在,我想将数组属性值与它所属的DOM元素配对,并且还能够找出与数组元素(属性)和DOM元素匹配的文本的指定部分.

Let's say that I have a website and I want to use script that loops trough its DOM elements and points out these elements that attribute contains part of specified text. I've managed to create a simple loop that finds every desired attribute of DOM element and creates array from it. Now I want to pair my array attribute value with DOM element that it belongs to and also be able to find out specified part of text that matches the array element (attribute) and DOM element.

var getAll = document.getElementsByTagName('*');
var myArray = [];

for (var i=0; i<getAll.length; i++) {
  getHref = getAll[i].getAttribute('href');
  if (getHref !== null) {
    myArray.push(getHref);
  }
}

我不知道如何将我的属性与DOM元素链接.我试图使用indexOf('')来查找文本的一部分,但是由于它在数组中查找完整的字符串,因此它不起作用.有人会这么友善地帮助我吗?我不想使用任何框架.

I have no clue how to link my attributes with DOM elements. I've tried to use indexOf('') to find part of text but it doesn't work since it looks for full strings in array. Would anybody be so nice and help me out? I don't want to use any frameworks.

推荐答案

现在我想将我的数组属性值与它的DOM元素配对 属于并且还能够找出文本的指定部分 匹配数组元素(属性)和DOM元素.

Now I want to pair my array attribute value with DOM element that it belongs to and also be able to find out specified part of text that matches the array element (attribute) and DOM element.

为什么不简单地仅使用包含选择器

Why not simply get only those elements that matches using the contains selector

var getAll = document.querySelectorAll("[href*='text-to-be-matched']");

这是一个NodeList,您可以使用 for-loop 进行迭代,并使用找到的内容对DOM元素进行索引.

This is a NodeList which you can iterate with for-loop and index the DOM elements with what you have found.

var attributeValToDOMMap = {};
getAll.forEach( function( element ){
   var hrefVal = element.getAttribute( "href" );
   attributeValToDOMMap[ hrefVal ] =  attributeValToDOMMap[ hrefVal ] || []; //in case one href value is common with multiple DOM elements
   attributeValToDOMMap[ hrefVal ].push( element );
});

这篇关于使用香草Javascript查找具有部分属性的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆