How to find the second id of something

Asked

Viewed 48 times

2

How can I get access to second div with id general as I tried in the script?

<div id="general">ds</div>
<div id="general">ds</div>`

alert($("#general").eq(2).html());

1 answer

7


This is not possible *because Ids must be unique. If you need to identify more than one element with a name, use classes instead of Ids:

<div class="general">ds</div>
<div class="general">ds</div>
var divs = document.querySelectorAll('.general');
alert(divs[0].innerHTML);
alert(divs[1].innerHTML);

* It’s actually possible, as other responses and comments show. But you should never repeat the ID in HTML, and so I don’t intend to show the tricks that allow you to select these elements with repeated Ids.

  • is correct but there is no gambiarra'?

  • Maybe if you look all document documents and check the id of each one you can. But I wouldn’t recommend doing this.

  • 2

    @user3163662 take a look here and learn how not to. Don’t use it, really. Fix the HTML.

  • I changed my HTML but now I come with another question to solve this. How can I find a div that contains a parameter eq=general in it? So... <div eq="general"></div> @Sergio @bfavaretto

  • 1

    @user3163662 Only this is an invalid attribute, okay? I would use <div data-eq="general"> (attributes with the prefix data- are valid in HTML5).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.