getElementsByName:按最后的部分名称控制 [英] getElementsByName: control by last partial name

查看:98
本文介绍了getElementsByName:按最后的部分名称控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过id获取div元素并仅使用部分名称first

I can get div elements by id and using only partial name "first"

html

<div id="first.1.end">first.1.end</div>
<div id="first.2.end">first.2.end</div>
<div id="two.3.end">two.3.end</div>
<div id="first.4.end">first.4.end</div>

js

function getElementsByIdStartsWith(selectorTag, prefix) {
    var items = [];
    var myPosts = document.getElementsByTagName(selectorTag);
    for (var i = 0; i < myPosts.length; i++) {
        if (myPosts[i].id.lastIndexOf(prefix, 0) === 0) {
            items.push(myPosts[i]);
        }
    }
    return items;
}
var postedOnes = getElementsByIdStartsWith("div", "first");
alert(postedOnes.length);

它计算3个div元素(警报)。

It counts 3 div elements (alert).

但是如何使用末端部分名称进行搜索?例如使用结束?

But how can I use end-partial name for search? For example using "end"?

推荐答案

来自 MDN属性选择器


[attr ^ = value]表示属性名称为attr和
的元素,其值的前缀为value。

[attr^=value] Represents an element with an attribute name of attr and whose value is prefixed by "value".

[attr $ = value]表示一个元素属性名称attr和
,其值后缀为value。

[attr$=value] Represents an element with an attribute name of attr and whose value is suffixed by "value".

所以你可以使用 [id ^ =first] 查找id以first开头的元素。并使用 [id $ =end] 查找以end结尾的元素

So you can use [id^="first"] to find elements with id start with "first". and use [id$="end"] to find elements end with "end".

喜欢

// This find all div which id ends with "end".
var divs = document.querySelectorAll('div[id$="end"]');

或使用jQuery:

$('div[id$="end"]');

此外,您可以将多个属性选择器组合在一起以查找更具体的元素:

Also, you can combine multiple attribute selectors altogether to find a more specific element:

// As we only use querySelector, it find the first div with id starts with "two" and ends with "end".
var divStartAndEnd = document.querySelector('div[id^="two"][id$="end"]');

参见 jsfiddle

这篇关于getElementsByName:按最后的部分名称控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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