jQuery Find by Id or Class Contains a Certain Text
Learn how jQuery Find by Id or Class Contains a Certain Text
Published
How to find all elements on a page whose element ID or class contains a certain text. It means we only want to find by part of Id or class not with complete name.
First id we are using is “DivIdTextSearchByPartOfIdCharacter” and we will find id that contains “PartOfId”. Also, we will look class name “DivIdTextSearchByPartOfClassName” and we will find class that contains “SearchByP”.
<script src="https://code.jquery.com/jquery-git.js"></script>
<div id="DivIdTextSearchByPartOfIdCharacter" >
Find element by Id contains text
</div>
<div class="DivIdTextSearchByPartOfClassName">
Find Elements by class contains text
</div>
We are using jQuery [attribute*=“value”] Selector. By adding sterik * in front of it search all elements in document with matching part of id or class like [attribute=“value”] Selector.
$('*[id*=PartOfId]:visible').each(function() {
$(this).text("Hurrah! Id find")
});
$('*[class*=SearchByP]:visible').each(function() {
$(this).text("Hurrah! class find")
});
$('[class*=PartOf]:visible').each(function(){
$(this).css('color', 'red');
});
Following is the complete executable code with jQuery library loaded.
Complete Code
<script src="https://code.jquery.com/jquery-git.js"></script>
<div id="DivIdTextSearchByPartOfIdCharacter" >
Find element by Id contains text
</div>
<div class="DivIdTextSearchByPartOfClassName">
Find Elements by class contains text
</div>
<script>
$('*[id*=PartOfId]:visible').each(function() {
$(this).text("Hurrah! Id find")
});
$('*[class*=SearchByP]:visible').each(function() {
$(this).text("Hurrah! class find")
});
$('[class*=PartOf]:visible').each(function(){
$(this).css('color', 'red');
});
</script>