How to capture certain part of the content of a div?

3

Hello, I have a div that has a certain height and content

<div class='mydiv'>

<p> blabalbalala </p>
<p> blabalbalala </p>
<p> blabalbalala </p>
<p> blabalbalala </p>

</div>

Assuming this div has a height of 100px , how do I capture only the first 30 px?

    
asked by anonymous 19.05.2015 / 22:21

2 answers

1

Following some suggestions from the comments I made the code below that iterates the child elements and compares the position relative to the parent element.

var div = document.querySelector('.mydiv'), val = 50, elements = [];
  for (var i = 0; i < div.children.length; i++) {
    if (div.children[i].offsetTop < val) {
      elements.push(div.children[i]);
    } else {
      break;
    }
}
console.log(elements);
<div class="mydiv">
  <p>blabalbalala</p>
  <p>blabalbalala</p>
  <p>blabalbalala</p>
  <p>blabalbalala</p>
</div>
    
20.05.2015 / 13:53
1

Here's a suggestion:

var els = Array.prototype.slice.call(document.querySelectorAll('.mydiv p'));

var incluidos = els.filter(function(el){
   return el.getBoundingClientRect().top < 30; 
});

incluidos.forEach(function(el){
   el.classList.add('incluido'); // ou correr outro código com esses elementos
});

example: link

This code creates a incluidos array with all elements p whose .top position is less than 30px.

    
20.05.2015 / 23:10