选择具有以特定值开始/结束的id属性的元素 [英] Select elements with id attribute that starts/ends with a particular value

查看:101
本文介绍了选择具有以特定值开始/结束的id属性的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下几段:

 < p id =item5_2> A< / p> 
< p id =item9_5> B< / p>
< p id =item14_2> C< / p>

我想改变id开头的段落内容 item 结尾于 2



我使用了以下jQuery:

  $(#item [\ d] * 2)。html(D); 

但它不起作用。我怎样才能使它工作?



JSFiddle演示

解决方案

是的,您可以将属性以开始,而属性以选择符结束

  $('[id ^ =item] [id $ =2]')。html(D); 

FIDDLE (您必须在小提琴中启用jQuery)



你不能使用正则表达式然而,匹配之间的数字,因为你需要 filter()

  $('[id ^ =item]')。filter(function(){
返回this.id.match(/ item \d + _2 /);
})。html(D);


Can jQuery or JavaScript be used with a regex to select multiple elements with similar id?

I have the following paragraphs:

<p id="item5_2"> A </p>
<p id="item9_5"> B </p>
<p id="item14_2"> C </p>

I want to change the content of paragraphs with id starting in item and ending in 2.

I used the following jQuery:

$("#item[\d]*2").html("D");

but it doesn't work. How can I get it to work?

JSFiddle Demo

解决方案

Yes it can, you can combine the attribute starts with and the attribute ends with selector

$('[id^="item"][id$="2"]').html("D");

FIDDLE (and you have to enable jQuery in the fiddle)

you can't use regex to match the numbers in between though, for that you'd need filter()

$('[id^="item"]').filter(function() {
    return this.id.match(/item\d+_2/);
}).html("D");

这篇关于选择具有以特定值开始/结束的id属性的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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