How do I select more than one element using the jQ

2019-07-27 04:16发布

问题:

I have two elements that I would like to select

<input id="iMe" /> and <span id="sMe">Blah</span>

I would like to select them both:

$("span[id$='Me']") and $("input[id$='Me']")

in one selector. I've tried:

$("span,input[id$='Me']") -> Nope
$("span[id$='Me'],input[id$='Me']") -> Nope
$("span[id$='Me']input[id$='Me']") -> Nope

I wouldn't mind just adding it to the collection either. I definitely don't want to create more script to hack around this. Any ideas?

回答1:

Example page: http://jsbin.com/idali (view/edit source at http://jsbin.com/idali/edit)

The following variations should all work:

$("span[id$=Me], input[id$=Me]")
$('span[id$=Me], input[id$=Me]')
$("span[id$='Me'], input[id$='Me']")
$('span[id$="Me"], input[id$="Me"]')

(edit: the original answer below is wrong; quotes are optional but allowed...)

You've got too much quoting in your attempts... You want

$("span[id$=Me],input[id$=Me]")

Attribute values are not quoted in css selectors.



回答2:

Why not give the two elements a class?

<input class="frobbable" id="iMe" /> and <span class="frobbable" id="sMe">Blah</span>

then

$(".frobbable")

?



回答3:

$('span[id$=Me]').add('input[id$=Me]')


回答4:

$('input#iMe, span#sMe');


回答5:

$("[id$='Me']")

should work. But watch out for the performance as this will have to go through the entire DOM.



回答6:

$("span[id$='Me'],input[id$='Me']") -> Yep

This really should work as well as the add() method, so maybe you have a problem somewhere else? Some ancient version of jQuery perhaps?