Gregory Mad
Gregory Mad

Reputation: 11

Insert a <br /> tag after x words <a> using jQuery

Any idea how make it with link? I try but nothing

<h3 class="wd-entities-title"><a href="#">WIANEK Amarylis bohaterem</a></h3>

$(".wd-entities-title").each(function() {
    var html = $(this).html().split(" ");
    html = html[0] + "<br>" + html.slice(1).join(" ");
    $(this).html(html);
});

http://jsfiddle.net/nd46b23L/

Upvotes: 1

Views: 90

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Slightly less verbose approach using html(function) which will iterate over all instances of matching selector <a> exposing the current html for each instance

Then use replace() to insert the break at first space and return the modified string

$(".wd-entities-title a").html((i, curr) => curr.trim().replace(' ', ' <br/>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title"><a href="#">WIANEK Amarylis bohaterem</a></h3>

Upvotes: 2

Kinglish
Kinglish

Reputation: 23654

The text you want to separate is inside an <a> tag - you should include that in your query or else the first space you'll encounter is the space in the <a> tag.

$(".wd-entities-title a").each(function() {
  var html = $(this).html().split(" ");
  html = html[0] + "<br>" + html.slice(1).join(" ");
  $(this).html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title"><a href="#">WIANEK Amarylis bohaterem</a></h3>

Upvotes: 3

Related Questions