0

I'm trying to match visible object's text but ignore not visible ones. By the way I need HTML code.

Here is my codepen.

Here is my HTML:

<div class="main">
   <div class="a">Hello</div>
   <div class="hid">Hello</div>
   <div class="b">Hello</div>
   <div class="hid2">Hello</div>
   <div class="c">Hello</div>
   <div class="hid3">Hello</div>
   <div class="hid4">Hello</div>
</div>

My CSS:

.hid, .hid2, .hid3, .hid4{
   display: none;
}

My JavaScript:

var regEx = /Hello/g;

var main = $('.main').html();

var matches = main.match(regEx);

console.log(matches);

Actually I want to exclude invisible elements without removing them from page. I want these HTML codes at the result:

<div class="a">Hello</div>
<div class="b">Hello</div>
<div class="c">Hello</div>

I don't want to remove the hidden objects because I'll use them interactively. I just want to exclude them from match. We can use jQuery.

Thank you from now.

sundowatch
  • 3,012
  • 3
  • 38
  • 66

3 Answers3

1

You can try with :visible selector like $('.main div:visible')

var visible = $('.main div:visible').map((_,i) => i.outerHTML).get();
console.log(visible);
.hid, .hid2, .hid3, .hid4{
   display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
   <div class="a">Hello</div>
   <div class="hid">Hello</div>
   <div class="b">Hello</div>
   <div class="hid2">Hello</div>
   <div class="c">Hello</div>
   <div class="hid3">Hello</div>
   <div class="hid4">Hello</div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

You can use the :visible selector to find all the divs under .main which are not hidden, and then output their outerHTML value if they match the regex:

var regEx = /Hello/g;

var visible = $('.main div:visible');
visible.each(function () {
   if ($(this).text().match(regEx)) {
      console.log(this.outerHTML)
   }
});
.hid, .hid2, .hid3, .hid4{
   display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
   <div class="a">Hello</div>
   <div class="hid">Hello</div>
   <div class="b">Hllo</div>
   <div class="hid2">Hello</div>
   <div class="c">Hello</div>
   <div class="hid3">Hello</div>
   <div class="hid4">Hello</div>
</div>
Nick
  • 138,499
  • 22
  • 57
  • 95
0
var regEx = /Hello/g;
$(".main div:visible").each(function(val, html){
   let inerHTML = $(this).html();
   console.log(inerHTML.match(regEx))
})