I’m working with feed that I have no control over. I need to replace the first half pipe character in each of a number of headlines with a <div> e.g.
<h3>New Clause 12 - Monitoring tool | Order | Committees</h3>
Changes to
<h3>New Clause 12 - Monitoring tool</h3><div> Order | Committees </div>
This script works, but it’s replacing all instances of | and replacing the entire contents of every h3 on the page with the content of the first headline. How can I limit the scope of the script to affect only the first | and leave the headlines text content unaltered?
jQuery('h3').html(jQuery('h3').html().replace('|', "</h3><div>"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>New Clause 12 - Monitoring tool | Order | Committees</h3>
>Solution :
Your approach unfortunately doesn’t work as you can’t split elements as you’re attempting. You can only amend/insert entire elements.
To do what you require, select the h3 element, get the text you require from it and place that in to a new div which you insert after the h3, like this:
$('h3').each((i, h3) => {
let $h3 = $(h3);
let text = $h3.text().split('|');
$h3.text(text[0].trim());
$('<div />').text(text.slice(1).join('|')).insertAfter($h3);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>New Clause 12 - Monitoring tool | Order | Committees</h3>
<h3>Foo | Bar | Foobar</h3>
<h3>Lorem | Ipsum | Dolor</h3>