开发者

How to identify a DIV without using an ID or a class name

开发者 https://www.devze.com 2023-03-06 23:51 出处:网络
So I just need a reminder, Every element can only have 1 id, but multiple classes are possible, But what if I would like to have 2 ways to uniquely identify an object without classes?

So I just need a reminder,

Every element can only have 1 id, but multiple classes are possible,

But what if I would like to have 2 ways to uniquely identify an object without classes?

I cant remember the name of it, something like Tagname, that can be used in addition to ID.

And how would you identify this object in jQuery?

For classes it is: $开发者_运维问答('.class'), for ID's it is $('#id') but what about this thing that I am vaguely describing?

Taylor


I cant remember the name of it, something like Tagname, that can be used in addition to ID.

You might be thinking of GetElementsByTagName() but that will return a collection: https://developer.mozilla.org/en/DOM/element.getElementsByTagName.

You can use arbitrary attributes in any modern browser (jQuery does this behind the scenes). So you can put whatever attribute you want on an element and locate it using a jQuery attribute selector (as @Dave pointed out in his answer).

<div myAttribute="foo"></div>

<script>

var element = $("div[myAttribute='foo']"); // matches all divs with "myAttribute" set

</script>

There are many options: http://api.jquery.com/category/selectors/


Just use the "name" attribute:

<div id="something" name="something"></div>

Then reference it by the id like usual, or by the name like this:

$('[name="something"]')

Info on on this selector here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号