big kev big kev - 1 year ago 63
Javascript Question

Is it possible to select one element from the array and use the attr() if you have elements with similar selectors

lets say you have two html elements with the same id , and you need to change the second element's attribute using the attr() jquery method .
Is it possible to do that because i keep getting an error saying that attr method is not a function .
Note that i have to use the element id .

<div id="div_el">ele_one</div>
<div id="div_el">ele_two</div>


$('#div_el'); // returns an array of all the DOM elements with div_el
var $el_two = $('#div_el').find(1);

$el_one.attr('style', 'background-color: green;');


Answer Source

As itsgoingdown said, you cannot select multiple ID elements. The ID is supposed to be unique. In a pinch, though, you could perhaps do this:

var $el_one = $('div#div_el').eq(1)

It's selecting on the div first, then the ID, and filtering by index (eg). Fiddle here.