简体   繁体   中英

What if I don't declare an ID in <div>?

How can I access any <div> if I don't declare the id attribute. Does DOM create ID itself?

eg

<div class="common_class" onmouseover="know_your_div(this)">
</div>

<script type="text/script">
   function know_your_div(obj){
     /* 
     Here i want to access the div object not by class because of it's common
     for all div
     */
   }
</script>

Well, the answer to your question is right there in your code.

The obj parameter that your know_your_div function takes is supplied as this in the onmouseover attribute. Thus, that is your div .

There's not an easy way to get to it in all browsers. Your best bet is to just create an ID on it. Is there a reason you can't?

Short of that, you have to navigate to it using DOM traversal methods, which are horribly unstable if your DOM structure changes at all. Code like:

document.body.childNodes[3].childNodes[2].childNodes[4];

or

document.getElementsByTagName('DIV')[22]; // 23rd DIV in the page

etc...

那么我想您需要在类名旁边明确指定ID。DOM不会自行创建ID ...

Then it's time to use the DOM. Maybe you could use things like firstChild, lastChild, nextSibling.. http://de.selfhtml.org/javascript/objekte/node.htm

If you're using a JS library, like MooTools or jQuery, which I reccomend, you'll have a lot of powerful selector magic at your hands (example http://mootools.net/demos/?demo=Slick.Finder ).

Why not use JQuery and selectors? http://api.jquery.com/id-selector/

No, the DOM does not create an ID. You need to add an ID. You can use jQuery to access a div by it's class.

The answer is in your Question, let me try to help you

<div class="common_class" onmouseover="know_your_div(this)"> </div>

var oldObject = "";
function know_your_div(obj) {

  // write ur condition if/ese/while/..

    obj.parentNode.do_Something(); OR obj.parentNode.ID/Class/value

    oldObject = obj;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM