Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
How to get only text and image from a div and ignore other html tags

I want to get the text and image tags from a div but need to ignore all the other HTML tags. So I wrote a regex to grab data from > <these tags. But it also removes the image tags also from my div ihtml. How do I resolve this issue?

I have tried so far,

HTML :

<div id="div-parent">

<p>
hello world <img src="" alt="image"/>
here we go
</p>
<ul>
  <li>test 1 <img src="" alt="image1"/> list 1</li>
  <li>test 2 <img src="" alt="image2"/> list 2</li>
  <li>test 3 <img src="" alt="image3"/> list 3</li>
  <li>test 4 <img src="" alt="image4"/> list 4</li>
  <li>test 5 <img src="" alt="image5"/> list 5</li>
</ul>
</div>

JQuery:

$(document).ready(function(){

var div = document.getElementById('div-parent')
console.log($(div).html().match(/(^[^<]+<)|(>([^<]+)<)|(>[^<]+$)/g))
//write a loop which iterates the text with image
});

I got the output something like this:enter image description here

Did I miss something? Is there any way to solve this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

try this

/[^<^>.]*<img [^<^>.]*\/>[^<^>.]*/g
about 4 years ago · Juan Pablo Isaza Report

0

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">  
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div id="div-parent">

<p>
hello world <img src="" alt="image"/>
here we go
</p>
<ul>
  <li>test 1 <img src="" alt="image1"/> list 1</li>
  <li>test 2 <img src="" alt="image2"/> list 2</li>
  <li>test 3 <img src="" alt="image3"/> list 3</li>
  <li>test 4 <img src="" alt="image4"/> list 4</li>
  <li>test 5 <img src="" alt="image5"/> list 5</li>
</ul>
</div>
 
<script>
$(document).ready(function(){

var div = document.getElementById('div-parent')
var el = $("#div-parent").find('p,li');
for (var i =0 ; i<el.length; i++) {
console.log(el[i].innerHTML);
}
console.log(el.length)
});

</script>
 
</body>
</html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!