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:
Did I miss something? Is there any way to solve this?
try this
/[^<^>.]*<img [^<^>.]*\/>[^<^>.]*/g
<!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>