Pawan
Pawan

Reputation: 2014

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?

Upvotes: 2

Views: 12338

Answers (2)

Ohhh
Ohhh

Reputation: 676

@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)
});

Upvotes: 5

Sotiris
Sotiris

Reputation: 40096

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.

Upvotes: 8

Related Questions