基于部分字符串的Javascript getElementById [英] Javascript getElementById base on partial string

查看:95
本文介绍了基于部分字符串的Javascript getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取元素的ID,但值是动态的,只是它的开头始终是相同的。

I need to get the ID of an element but the value is dynamic with only the beginning of it is the same always.

下面是一段代码。

<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite">

ID始终以'poll-'开头,然后数字是动态的。

The ID always starts with 'poll-' then the numbers are dynamic.

如何使用JavaScript而不是jQuery获取ID?

How can I get the ID using just JavaScript and not jQuery?

推荐答案

可以使用 querySelector

document.querySelector('[id^="poll-"]').id;

选择器意味着:获取属性 [id] 以字符串poll - 开头。

The selector means: get an element where the attribute [id] begins with the string "poll-".

^ 匹配开始

* 匹配任何位置

$ 匹配结尾

^ matches the start
* matches any position
$ matches the end

这篇关于基于部分字符串的Javascript getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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