How can i split the string containing
tag using jquery. I tried the following code but it get error in console. I am not sure how to split the strin
Here is the Working code
jQuery(document).ready(function($)
{
var lines = 'this is for testing <br/> How are you<br/>'.split('<br/>');
alert("workig");
jQuery.each(lines, function() {
alert(this);
});
});
jQuery(document).ready(function($)
{
var str = 'this is for testing <br/> How are you<br/>';
var lines = str .split('<br/>');
jQuery.each(lines, function() {
alert(this);
});
});
No need to wrap in jquery like :
jQuery('this is for testing <br/> How are you<br/>').split('<br/>');
Can be like :
('this is for testing <br/> How are you<br/>').split('<br/>');
DEMO
That's no jQuery solution, but hopefully somebody will find it useful. The function returns one or two elements.
function splitContentsOnBr(el) {
const before = document.createElement('div');
const after = document.createElement('div');
let found = false;
el.childNodes.forEach(c => {
if (found) {
after.appendChild(c.cloneNode(true));
} else if (c.tagName == 'BR') {
found = true;
} else {
before.appendChild(c.cloneNode(true));
}
});
return after.childNodes.length ? [before, after] : [before];
}
document.querySelector('#result').innerHTML = splitContentsOnBr(document.querySelector('h1'))
.map(el => el.textContent.trim())
.join(', ');
<h1>
First part
<br>
Second part
</h1>
<div id="result">
</div>