jquery - finding elements by attributs
For example if I have html like this:
<div id="id">
<div class="class1">
<div class="class2" name="name1"></div>
<div class="class2" name="name2"></div>
<div class="class2" name="name3"></div>
</div>
</div>
And I have many divs with di开发者_Go百科ffrent id values. It is possible to find and choose element by name attribute's value when having <div id="id">
as a start point?
Yes, of course, using the "attribute equals" selector, e.g.:
$('#id div[name="foo"]').
will find all divs with name="foo"
that are descendents (direct or otherwise) of the div with ID id
.
You can do this also i think
$('div').attr('custom:attr')
Here an example how to directly select an tag by its parameter :
$('div[name=name1]').dosomething();
Should you want to add 'name' attribute next to 'id' after page loads use:
$(document).ready(function() {
$('div#id').attr('name','name1');
});
You can do this using jQuery selectors. http://api.jquery.com/category/selectors/
Something like this would give you one of your div elements.
$('div[name=name1]')
You can use this approach for other attributes as well. As the selector is merely a string, you can easily construct your selector from a block of javascript.
精彩评论