-1

I need to find out the content before <img> tag in my HTML if it does not have <br/> before it. And if <img> jas some other content before it then I need to add <br/> before it.

Shiv Kumar Ganesh
  • 3,799
  • 10
  • 46
  • 85
castors33
  • 477
  • 10
  • 26

2 Answers2

1

Consider this html code :- (This solution uses JQuery!)

<h1><img src="#"/><h1>
<br/><img src="#"/>

Now in one case you need to get the element before <img>

  $(document).ready(
function(){
 $('img').each(function(){
  if($(this).prev()==$('br'))
   {
      $(this).prev().replaceWith('');
   }
   if($(this).prev()!=$('br)')
        {
          $(this).prev().replaceWith('br');
        }
});

});

Guess this would solve your problem.

Shiv Kumar Ganesh
  • 3,799
  • 10
  • 46
  • 85
1

A slightly simpler and faster version

$(document).ready(function(){

    $('img').each(function(){
         var prev = $(this).prev();
         if (prev[0] && prev[0].nodeName.toUpperCase() !== 'BR') {
            prev.after('<br>')
         }
   })

})
SMathew
  • 3,993
  • 1
  • 18
  • 10