2

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?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1: great solution. I suggested a small change: index+1 instead of index behaved closer to what I wanted in Safari.
This will not trigger automatically upon new dynamic data showing up in the DOM. This will only add the tabindex attribute to the matching existing DOM elements at the moment this code is executed. You can either re-run this each time something new shows up, or better yet, watch the body and find your elements from there.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.