简体   繁体   中英

mootools get position of an element which has no ID

I'm relatively new to the whole Javascript thing, except for some basic jQuery stuff.

Recently I took over a small local project that uses mootools and I'm stuck.

I have several pages with a relative simple dom structure and content that is stored in a database. The first element on each page is either a div or a paragraph with fixed width and height.

There are three variations of said element, each of them differs in height, which means that we have either one of these on every page

<div class="header1"><img ...></div>
<p class="header2"><img ...></p>
<p class="header3"><img ...></p>

Each of these are followed by several paragraphs containing text or images.

My Problem: I have to put a small div with a print icon between the page's first element (div or p) and the following content but I'm not allowed to change any of the code that generates this page.

The Idea is to use mootools (which is loaded anyway) to place the div on an absolute position just below the first element.

This could be done quite easily with jQuery, but I have to use mootools plus the elements do not have IDs.

Is there any easy way to get the position of either , or on page load and then placing (position: absolute;) a div right under it?

So far I have this, (which is quite poor) which logs the the elemnent with a class "header1"

window.addEvent('domready', function() {
$$('.header1').each(function(element){
    console.log(element);
});

});

element.getPosition() gets you the x and y positions of an element, which should allow you to create a new element positioned around there somewhere. getPosition() could be in MooTools More, depending on the version you're using.

Adding a new element to the DOM at an appropriate place without the tricky positioning might be easier, though that will depend on your DOM.


Judging your reactions from comments, if you simply wanted to match a single element in the document by something else than an id, document.getElement() is what you need, which will do about the same as $$() , but return the first match or null if nothing matched.

Yes of course. The question is how to get the element you want if it has no ID. This is as hard as in jQuery or as easy as in jQuery.

Take a look at mootools documentation of Element.getPosition() .

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