Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

jquery - Select an element when the class name starts with a certain word

Suppose I have the elements as below:

<div class="home">
    <div class="tab231891230"></div>
    <div class="tab121232441"></div>
    <div class="tab123134545"></div>
</div>

How can I use jQuery to select the div element that the class starts with "tab"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is called the Attribute Starts With Selector. My example sets a red text color on the elements:

$('[class^="tab"]').css('color', 'red');

jsFiddle Demo

Please note that if the elements have more than one class and the other precedes the one with tab inside (class="nyedva tab231891230") the element won't be selected by this selector.

If you want to select even these, you can use this example:

$('.home div').filter(function () {
    return this.className.match(/tab/);
}).css('color', 'red');

jsFiddle Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...