简体   繁体   中英

How do I add a tab Index for dynamically created elements using Javascript?

I need some help in adding a tabindex to all the elements in a <div> dynamically. I need to do this for accessibility. If I specify a <div> element, it should automatically add the tabindex to all elements in that <div> .

I tried some thing like this:

$('#Latest-News-Content [tabindex]').each(function () {
    $(this).attr( 'tabindex', parseInt( $(this).attr('tabindex') ) + 10 )
});

but it doesn't seem to work. Also, how can I add a tab index for elements which are hidden?

For example:

I have a title and description showing in a <div> . The description is hidden and has a jQuery collapser . When I click on the title the description expands. How can I set a tabindex for all the elements?

Here an example that adds tabindex for all a tags

$('#Latest-News-Content a').each(function(index) {
    $(this).attr('tabindex', index)
});

Demo: http://jsfiddle.net/azk2n/1

You can use the same method for hidden elements.

@Sotiris

This might be an update with newer versions of jQuery. Use.prop() instead of.attr() to set property values.

$('#Latest-News-Content a').each(function(index) {
    $(this).prop('tabindex', index)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM