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

查看:83
本文介绍了基于部分字符串的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天全站免登陆