How to capture a certain part of a div’s content?

Asked

Viewed 53 times

3

Hello I have a div which has a certain height and content

<div class='mydiv'>

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

</div>

Supposing that this div have a height of 100px, how do I capture only the first 30 px?

  • 4

    What exactly do you want to do? You’re going to use this 30px height for what?

  • @Erloncharles I want to divide in other Ivs this div with size 100px

  • 1

    @Rod What about the content? Wouldn’t it be better to work with an x number of lines?

  • 1

    You can calculate which element is intercepted by the 30px line. And this element must be included or excluded.

  • @Renan has a div with 100px, I want to capture the 20 px primeirios and add the page:[] content in an array, so this array should contain 5 items

  • 1

    The question is interesting, but what everyone here must be wondering is why you need it. It’s very unusual.

  • @bfavaretto is to style these separate Ivs as a A4 page, however I want to know how to manipulate the nodes of that content div

  • 2

    And if the 30px falls in the middle of an element, what do you want to do with it?

  • @bfavaretto the idea is to add also with push

Show 4 more comments

2 answers

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: http://jsfiddle.net/dqba9qen/

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

1

Following some suggestions of the comments I made the code below that iterates the child elements and compares the position in relation 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>

Browser other questions tagged

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