Reputation: 3430
Using a div as selector is easy:
<div id="test1"></div>
$('#test1').doSomething();
I want to target only another div, containing the same ID
+ _sub
:
<div id="test1"></div>
<div id="test1_sub"></div>
$('#test1').find( /* Same ID + "_sub" */ ).doSomething();
How can I do this? I know I can use .attr('id')
to take #test1, but I do not how to extend this with _sub.
Of course it would be easy to target the #test1_sub
directly, but image I have 1000 divs counting up test1
, test2
, test3
, etc. and want to use this inside of a function.
Upvotes: 0
Views: 67
Reputation: 984
Set a variable and chain: (CORRECTED)
var target = $(whatever test div you targetted).attr('id');
$('#'+target + "_sub").doSomething();
You said you were going to use it in a function, so it would be targettable this way for example. Lets say when you click #test1
a function will run on all subs based on the clicked test:
$('.testBoxes').click(function () {
var target = $(this).attr('id');
$('#'+target + "_sub").doSomething();
});
Upvotes: 2
Reputation: 5462
Here you can use start with selector to work with all ids.
$(document).ready(function(){
$( "*[id^='test1']" ).fadeOut();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="test1">Test 1</div>
<div id="test1_sub"> Test 1 Sub</div>
<div id="test1_asdf">Test 1 ASDF</div>
<div id="test1_sub342"> Test 1 sub342</div>
<div id="test1_sdfsd">Test 1 sdfsd</div>
<div id="test1_45645"> Test 1 45645</div>
Upvotes: 2
Reputation: 2267
You do it like this
$('#test1' + "_sub").fadeOut();
Note the quotation-marks containing "_sub".
EDIT: In your answer, you made up an example where you had 100 divs with ids like test1
, test2
and so on. Then you could select all elements with an id beginning with test
. Like this:
$('*[id^="test"]').fadeOut();
Upvotes: 2