There is a code

function addBr() { if ($(window).width()<=750) { $('.journal img').each(function () { if ($(this).not('br')) { $(this).after('<br>'); alert('<br> созданы'); } else { return false; } }) } else { $('.journal').each().remove('br'); } } $(window).load(addBr); $(window).resize(addBr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="journal"> <p><span>1</span><img src="img/file1.png" alt=""> учебных журнала в месяц</p> </div> <div class="journal"> <p><span>2</span><img src="img/file2.png" alt=""> учебных журнала в месяц</p> </div> <div class="journal"> <p><span>3</span><img src="img/file3.png" alt=""> учебных журнала в месяц</p> </div> 

help me figure out why every time the window is resized,
are created again and again. and when you change the window large from 750px side
not deleted

  • What do you want to do? Why do you need to insert <br> with less than 750? - MihailPw

1 answer 1

First, you incorrectly checked for the next item. You need to hard check whether the following element is <br> : $(this).next().prop("tagName") !== "BR" .

Secondly, the documentation has examples on .each() . It is required to transfer the function and delete the elements.

Thirdly, I do not understand why you need such a solution at all.

Here is a specific decision on your question:

 function addBr() { if ($(window).width() <= 750) { $('.journal img').each(function() { if ($(this).next().prop("tagName") !== "BR") { $(this).after('<br>'); } else { return false; } }) } else { $('.journal br').each(function() { $(this).remove() }); } } $(window).load(addBr); $(window).resize(addBr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="journal"> <p><span>1</span><img src="img/file1.png" alt=""> учебных журнала в месяц</p> </div> <div class="journal"> <p><span>2</span><img src="img/file2.png" alt=""> учебных журнала в месяц</p> </div> <div class="journal"> <p><span>3</span><img src="img/file3.png" alt=""> учебных журнала в месяц</p> </div> 

As a variant with media query :

 @media (min-width: 750px) { .hide-large { display: none; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="journal"> <p><span>1</span><img src="img/file1.png" alt=""><br class="hide-large"> учебных журнала в месяц</p> </div> <div class="journal"> <p><span>2</span><img src="img/file2.png" alt=""><br class="hide-large"> учебных журнала в месяц</p> </div> <div class="journal"> <p><span>3</span><img src="img/file3.png" alt=""><br class="hide-large"> учебных журнала в месяц</p> </div>