I have this content:
<div class="newscontent">
<p class="article-lead">
Lorem ipsum dolor sit amet, in laoreet fermentum, ac turpis quam, libero in
tincidunt orci at, nec sociosqu, accumsan sed eget pretium libero deserunt
suscipit.
</p>
Lectus lobortis aenean odio posuere tellus non, tincidunt urna nec rhoncus
wisi, turpis eros duis lorem dui sagittis, convallis arcu vestibulum non ad
non.<br /><br />
<br /><br />Lacinia aliquet, adipiscing egestas, quae consectetuer vel, nulla
mattis aenean quam risus commodo. Egestas ipsum nunc vitae amet. Proin
molestie, in rhoncus, in pellentesque vitae aliquam quis suscipit lorem, eu
metus quis adipiscing tempus ante. Donec non morbi parturient. Libero nam
pretium ipsum adipiscing risus cras.<br /><br />
<br /><br />Ultrices elit nec mauris, ante consequat, nec sapien mi pharetra.
Quam proin, non sem tortor, dis odio et. Justo lectus quis, tincidunt praesent
fermentum eu, quis risus, tempor at eros id nunc eget urna, at sem pulvinar
ullamcorper accumsan.<br /><br />Etiam maecenas leo eget, aliquet faucibus mi
lectus erat rhoncus turpis. Velit tristique ante. Morbi et ipsum at dolor
nunc, tristique sed gravida in eu molestie viverra.
</div>
And i want to remove multiple multiple <br><br/> to one <br><br/> between two paragraphs.
var ta = document.getElementById('b');
ta.innerHTML = ta.replace("<br><br/><br><br/>", "<br><br/>");
<div class="newscontent">
<p class="article-lead">Lorem ipsum dolor sit amet, in laoreet fermentum, ac turpis quam, libero in tincidunt orci at, nec sociosqu, accumsan sed eget pretium libero deserunt suscipit.</p>
Lectus lobortis aenean odio posuere tellus non, tincidunt urna nec rhoncus wisi, turpis eros duis lorem dui sagittis, convallis arcu vestibulum non ad non.<br/><br/> <br/><br/>Lacinia aliquet, adipiscing egestas, quae consectetuer vel, nulla mattis aenean quam risus commodo. Egestas ipsum nunc vitae amet. Proin molestie, in rhoncus, in pellentesque vitae aliquam quis suscipit lorem, eu metus quis adipiscing tempus ante. Donec non morbi parturient. Libero nam pretium ipsum adipiscing risus cras.<br/><br/>
<br/><br/>Ultrices elit nec mauris, ante consequat, nec sapien mi pharetra. Quam proin, non sem tortor, dis odio et. Justo lectus quis, tincidunt praesent fermentum eu, quis risus, tempor at eros id nunc eget urna, at sem pulvinar ullamcorper accumsan.<br/><br/>Etiam maecenas leo eget, aliquet faucibus mi lectus erat rhoncus turpis. Velit tristique ante. Morbi et ipsum at dolor nunc, tristique sed gravida in eu molestie viverra.
</div>
Okay your problem is you are not taking the element in the right way, and also, you cant make a replace of an HTML element, you have to make replace of a string, so first change replace for an '.innerHTML.replace', and then change your replaces words. Here the correction ;)
var ta = document.getElementsByClassName('newscontent')[0];
console.log(ta.innerHTML);
ta.innerHTML = ta.innerHTML.replace(/<br><br>/gi, "<br>");
console.log(ta.innerHTML);
A regular expression will sort this right out for you.
To match explicitly a series of 4 <br />s (in varying formats), you want a regex like this:
/(<br[^\/>]*\/?>\s*){4}/gi
This works like so:
<br matches the start of our tag
[^>\/]* matches zero or more characters other than > or /
\/? optionally matches a /
> matches the end of our tag
\s* matches zero or more whitespace characters.
(...){4} matches exactly 4 instances of whatever's between ( and )
So, used in your code, it'll look something like this:
ta.innerHTML = ta.innerHTML.replace(/(<br[^\/>]*\/?>\s*){4}/gi, '<br /><br />');
Naturally, if you wanted to, instead, replace any 2 <br />s with a single one, I'm sure you can figure out what to change!
Related
This question already has answers here:
Regex to match words with hyphens and/or apostrophes
(7 answers)
Closed 4 months ago.
I am wondering about this case:
Is it possible to do something like that?
if word, for example co-worker is hyphen, jquery can take detect and take word and replace with class inside?
Example:
<span class="hyphenated-word">co-worker</span>
I think something about preg.replace function, but not sure how to detect word.
Can anybody give me a tip for this?
You could use a regex to detect any hyphenated word:
function highlightHyphenated(element) {
// Regular expression matching any group composed by:
// - `[A-Za-zÀ-ÖØ-öø-ÿ]+` one or more letters (including accented ones), followed by
// - `-` a hyphen, followed by
// - `[A-Za-zÀ-ÖØ-öø-ÿ]+` one or more letters (including accented ones)
const re = /([A-Za-zÀ-ÖØ-öø-ÿ]+-[A-Za-zÀ-ÖØ-öø-ÿ]+)/gim;
if (re.test(element.innerText)) {
element.innerHTML = element.innerHTML.replace(re, '<span class="hyphenated">$1</span>');
}
}
document.querySelectorAll('p').forEach(el => highlightHyphenated(el));
.hyphenated {
display: inline-block;
background-color: yellow;
font-weight: bold;
}
<p>Lorem ipsum dolor sit-amet, consectetur adipiscing elit. Etiam orci tortor, aliquet quis mollis in, posuere id ipsum. Vestibulum quis nibh augue. Sed id congue ex. Suspendisse eget elit fringilla, commodo mi vitae, luctus odio. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque cursus quam vitae leo eleifend, a laoreet neque varius. Morbi quis posuere risus, at scelerisque dui. Morbi sit amet lorem purus. Pellentesque auctor ut libero sed tempor. Integer vitae erat id leo porttitor blandit. Duis cursus lacus quis mauris facilisis, dapibus auctor nisl feugiat. Donec consectetur dolor eu suscipit aliquam. Fusce magna ante, luctus a arcu at, volutpat blandit tortor. Vivamus bibendum sem id mauris dapibus, et ultricies elit fermentum. Aliquam eu efficitur ipsum. Pellentesque eu velit ipsum.</p>
<p>Sed-fermentum lorem a ipsum sodales, vel vestibulum odio hendrerit. Aenean auctor ipsum in urna finibus, eu vulputate massa rutrum. Curabitur id eros pulvinar, dapibus justo nec, euismod sem. Ut ornare turpis velit, non aliquet est rhoncus eu. Etiam ex dolor, congue eleifend nisl eget, tempus dictum nulla. Integer ultricies enim eu mattis sagittis. Aliquam malesuada condimentum semper. Aliquam erat volutpat. Integer in dapibus sapien, tempor venenatis nisi. Curabitur eget sapien vitae nisi pulvinar volutpat aliquet ut augue. Cras pretium congue est, at pulvinar velit egestas vitae. Pellentesque non dui et urna posuere mattis.</p>
<p>Fusce consectetur vel purus a rutrum. Nulla vitae-metus nec eros facilisis porta. Ut quis sem ac nibh finibus porta egestas ac neque. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque sagittis nisl ante, vel placerat dui fermentum eu. Quisque placerat placerat neque. Nullam vel euismod nisl. Nullam aliquet enim vitae odio ultricies tincidunt. Nullam sagittis arcu at eleifend commodo. In hac habitasse platea dictumst. Nunc nibh lacus, pharetra nec sapien quis, congue pharetra felis. Vivamus porta, ex et convallis sagittis, ex dui porttitor augue, et tempus neque risus quis diam. Morbi eget leo lectus.</p>
<p>Sed at justo euismod, luctus lorem ut, dignissim libero. Curabitur vel auctor neque, vel ultrices nulla. Duis in aliquet-ligula. Aliquam sed est nisl. Aliquam enim orci, congue eget erat sed, imperdiet pharetra est. Fusce efficitur a tortor-nec fringilla. Sed sed tempus tellus, efficitur ornare lorem. Proin risus sem, mollis et lectus nec, rhoncus accumsan magna. Mauris hendrerit ligula eu est pretium, id bibendum ante tincidunt. Nam cursus vehicula diam, in eleifend magna blandit at. Vestibulum sit amet bibendum elit.</p>
<p>Donec magna est, placerat in vehicula eget, convallis non metus. Proin posuere ultricies neque a scelerisque. Quisque eu ex quis magna varius-vulputate. Sed venenatis dapibus iaculis. Cras lacinia ex et ante mollis, et condimentum ante porta. Sed tempus diam at fringilla condimentum. Aenean est ex, sollicitudin at blandit ac, dapibus eu mauris. Sed a tincidunt arcu. Maecenas sagittis cursus eros, ut commodo neque maximus id. Aenean accumsan purus eu tortor eleifend, vel volutpat turpis tempus. Vestibulum et metus non eros rhoncus placerat. Donec congue enim libero. Cras placerat, urna eu tincidunt aliquam, nisl odio viverra felis, id volutpat ipsum libero a leo.</p>
If you do not care about accented letters, you can replace [A-Za-zÀ-ÖØ-öø-ÿ]+ with [A-Za-z]+
I'm trying to count the number of words present in a string. This string is composed by 3 paragraphs with 281 words.
I'm using the split.length method, but the word counting I'm getting is 279 and not 281. Can't figure out what I'm doing wrong in order to be missing 2 words from the counting. Can you help please?
const loremIpsumString = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis imperdiet ornare ante, iaculis facilisis elit bibendum pulvinar. Vestibulum nec tempor libero, vitae ullamcorper arcu. Pellentesque tempor euismod viverra. Donec et mi at leo ultrices elementum sed sed lectus. Quisque aliquam, urna cursus ornare accumsan, eros turpis sagittis dui, efficitur placerat orci ex sit amet est. Nunc sodales neque elit, quis consequat magna tristique ac. Suspendisse potenti. Nunc volutpat pulvinar neque, non interdum felis varius eget. Praesent dictum eros a purus tempor, et pellentesque ipsum dictum. Nulla ac magna nisl.
Quisque vulputate convallis ex nec venenatis. Nunc hendrerit tristique dictum. Integer posuere sed libero id vestibulum. Aliquam quis elit et massa varius euismod. Maecenas et imperdiet neque. Phasellus aliquet purus sed enim pharetra tempus. Ut euismod facilisis enim, quis dictum nulla pulvinar quis. Donec a est leo. In hac habitasse platea dictumst. Proin fringilla, quam et feugiat pretium, erat augue pretium eros, ac facilisis eros lectus vel ipsum.
Donec dui libero, sagittis eget auctor sed, dictum in orci. Mauris mollis fermentum purus nec aliquet. In ultricies mi sed tortor vehicula, ut semper ex posuere. Suspendisse commodo massa non sem porta suscipit. In finibus neque vel dolor malesuada mattis. Etiam tincidunt mattis velit nec viverra. Nulla facilisi. Mauris eu odio pharetra, vehicula augue sit amet, accumsan tortor. Sed tempus metus ac gravida scelerisque. Aenean ullamcorper orci id ipsum bibendum, a sollicitudin ligula sagittis. Integer id tellus sit amet enim faucibus consequat. Duis nisi purus, volutpat sit amet fermentum eu, tincidunt non purus. Praesent leo orci, tempor et felis non, suscipit lacinia mi. Nulla a justo sed elit tincidunt imperdiet. Aenean hendrerit vehicula odio, sit amet cursus eros aliquet non. Vestibulum vulputate scelerisque ultricies.`;
const numWords = (loremIpsumString.split(" ").length);
console.log(numWords);
Many thanks!
You're splitting the text by the literal space, so the words that are on paragraph boundaries are considered a single "word", e.g. nisl.\n\nQuisque. You need to split by any whitespace instead, using a regular expression:
const numWords = loremIpsumString.split(/\s+/g).length;
This MDN guide provides an introduction to regular expressions.
When working with dynamic strings, it would be also a good idea to remove leading and trailing whitespace before counting:
const numWords = someString.trim().split(/\s+/g).length;
const regexConst = /[a-zA-Z]\w*/g
const loremIpsumString = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis imperdiet ornare ante, iaculis facilisis elit bibendum pulvinar. Vestibulum nec tempor libero, vitae ullamcorper arcu. Pellentesque tempor euismod viverra. Donec et mi at leo ultrices elementum sed sed lectus. Quisque aliquam, urna cursus ornare accumsan, eros turpis sagittis dui, efficitur placerat orci ex sit amet est. Nunc sodales neque elit, quis consequat magna tristique ac. Suspendisse potenti. Nunc volutpat pulvinar neque, non interdum felis varius eget. Praesent dictum eros a purus tempor, et pellentesque ipsum dictum. Nulla ac magna nisl.
Quisque vulputate convallis ex nec venenatis. Nunc hendrerit tristique dictum. Integer posuere sed libero id vestibulum. Aliquam quis elit et massa varius euismod. Maecenas et imperdiet neque. Phasellus aliquet purus sed enim pharetra tempus. Ut euismod facilisis enim, quis dictum nulla pulvinar quis. Donec a est leo. In hac habitasse platea dictumst. Proin fringilla, quam et feugiat pretium, erat augue pretium eros, ac facilisis eros lectus vel ipsum.
Donec dui libero, sagittis eget auctor sed, dictum in orci. Mauris mollis fermentum purus nec aliquet. In ultricies mi sed tortor vehicula, ut semper ex posuere. Suspendisse commodo massa non sem porta suscipit. In finibus neque vel dolor malesuada mattis. Etiam tincidunt mattis velit nec viverra. Nulla facilisi. Mauris eu odio pharetra, vehicula augue sit amet, accumsan tortor. Sed tempus metus ac gravida scelerisque. Aenean ullamcorper orci id ipsum bibendum, a sollicitudin ligula sagittis. Integer id tellus sit amet enim faucibus consequat. Duis nisi purus, volutpat sit amet fermentum eu, tincidunt non purus. Praesent leo orci, tempor et felis non, suscipit lacinia mi. Nulla a justo sed elit tincidunt imperdiet. Aenean hendrerit vehicula odio, sit amet cursus eros aliquet non. Vestibulum vulputate scelerisque ultricies.`;
const totalWords = loremIpsumString.match(regexConst).length
console.log(totalWords)
will console.log the total amount of words (DOESNT WORK WITH ACCENT MARKS)
I'm in need to split HTML string for further processing by my side. I have a string that contains all the HTML.
My needs keeps only in split all of them in an array, mantaining the tags. It should be splitted by <p>
As my further searches, it's better to not use regular expressions for that, so I need to find a proper way to do it in javascript or jquery without using external libs.
What's the best way to do it.
If it would be to use regex, it would be something like this:
str.match(/<p(.)>.*?<\/h\1>/g);
HTML example:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus porttitor quam ut ullamcorper aliquam. Morbi in dapibus tellus. Phasellus lobortis ex sapien, nec malesuada ante vulputate blandit. Nullam lacinia neque mi, at iaculis ante condimentum sed. Sed luctus purus vel dictum posuere. Ut auctor lorem a <b>congue tincidunt</b>. Nulla ut ipsum libero. Aliquam erat volutpat. Donec gravida dui quis pulvinar molestie. Duis nec lacus sem. Mauris tellus nibh, tempus at mauris id, tempus eleifend libero. Nam laoreet congue suscipit. Duis sollicitudin ex eu elementum commodo.</p>
<p>Cras finibus imperdiet sapien, id sodales enim tempus sit amet. Vivamus ac ligula sagittis ante sollicitudin viverra. Pellentesque accumsan placerat massa, et aliquet purus commodo et. Aliquam molestie orci nec vehicula fermentum. In gravida ligula tempor dolor feugiat, vitae facilisis nisi facilisis. Vivamus sodales eros non vehicula scelerisque. Mauris suscipit vitae erat eu fermentum. Aenean pellentesque ut arcu consectetur malesuada. Aenean posuere ante sit amet nibh rhoncus mattis. Fusce at aliquam elit, sit amet ultrices purus. Quisque quis risus eleifend, commodo est auctor, tincidunt dui. Aliquam eros urna, tristique nec felis vel, varius eleifend nulla. Suspendisse vestibulum posuere felis in vestibulum. Nunc sit amet maximus libero. <i>Nulla placerat congue</i> lectus a ultrices.</p>
But since we shouldn't use it, how can I achieve this?
Thanks.
I got an layout using bootstrap with multiple floating divs.
I want to retrieve the space between the divs using JavaScript. Ive only no idea how i can do this. See below picture.
A picture says a 1000 words ;)
Ive created a fiddle with above layout, i will paste it here so you can play with it if you want.
.page-container {
background: #ededed;
padding: 40px 0;
}
.column {
padding: 15px;
background-color: white;
box-shadow: 1px 1px 3px #ccc;
}
[class^="col-"] {
margin-bottom: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="page-container">
<div class="container">
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="column">
<h2>
Floating element #1
</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
</p>
<p>
Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
</p>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="column">
<h2>
Floating element #2
</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
</p>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="column">
<h2>
Floating element #3
</h2>
<p>
Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
</p>
<p>
Fusce a velit et justo porttitor sollicitudin a a velit. Praesent ultrices arcu a sodales ultricies. Etiam cursus mattis dapibus. Fusce vulputate commodo pretium. Suspendisse a orci vitae ipsum interdum dapibus a quis velit. Proin euismod, lectus id euismod semper, tellus nunc luctus dui, consectetur venenatis erat mi eu dolor. Nunc eleifend semper lacus, at hendrerit massa. Praesent ac magna at lacus commodo faucibus eu sit amet magna. Donec pellentesque felis et leo interdum dignissim. Sed sit amet sapien ac quam auctor semper quis ut nibh. Vivamus consectetur, ipsum luctus semper viverra, sem arcu sagittis mauris, a interdum odio sapien in augue.
</p>
<p>
Nam ut bibendum urna, sed congue neque. Nunc a nunc venenatis, porttitor odio vitae, finibus est. Suspendisse quis purus a diam aliquam ullamcorper eu sed dolor. Etiam ac eros eget nisl pretium lobortis. Nulla convallis id nunc eget efficitur. Morbi vel elementum justo. Phasellus et egestas quam. Cras eu tristique urna. Cras ac justo efficitur, consectetur eros et, tincidunt nulla. Quisque et cursus ipsum. Ut tincidunt, purus et tempor fermentum, nulla diam suscipit ex, non sodales eros nunc vel ante. Duis quis justo quam. Sed imperdiet lorem et blandit pretium. Etiam elit dui, tristique et vehicula vitae, venenatis et augue.
</p>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="column">
<h2>
Floating element #4
</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
</p>
<p>
Curabitur quam sapien, lacinia sit amet sagittis sed, fringilla nec arcu. Morbi at velit facilisis, aliquet justo non, tincidunt mauris. Curabitur tempus ante sit amet auctor fringilla. Sed ut velit ac purus euismod placerat. Fusce ultrices feugiat tortor at condimentum. Ut eleifend eget velit at vulputate. In commodo ligula et urna ultrices, non ullamcorper est pharetra. Donec pharetra, purus a aliquam rutrum, lacus arcu porttitor nunc, eu maximus eros justo sed neque. Fusce a urna non enim lobortis venenatis. Suspendisse potenti.
</p>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="column">
<h2>
Floating element #4
</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus finibus ullamcorper commodo. Donec volutpat porttitor elit sit amet aliquet. Nam eget felis vel sapien tempus tincidunt placerat ac lectus. Donec malesuada, est ac accumsan porta, leo augue varius ante, ut cursus tortor mauris non ipsum. Vestibulum nec odio diam. Integer gravida varius risus quis euismod. Donec iaculis velit vitae semper bibendum. Donec et volutpat ligula. Sed in elit et risus facilisis maximus. Cras tempor sollicitudin velit, a mattis elit molestie non. Maecenas vitae eros in leo feugiat maximus at porttitor mauris. Vivamus vulputate tellus laoreet neque vulputate suscipit sit amet eget ipsum. Donec faucibus dignissim erat, at bibendum dui laoreet eget.
</p>
</div>
</div>
</div>
</div>
Im trying to get those pixel, and move the underlying div up using JavaScript. I know i can use something like masonry. But i can't get those working in my application.
Does anyone have an idea how i can do this? (oh, using jQuery is no problem)
Try one of:
var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;
clientHeight includes the height and vertical padding.
offsetHeight includes the height, vertical padding, and vertical borders.
scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
with JQuery
$('#someDiv').height();
$('#someDiv').width();
Get first element's x,y cordinates (e.g Retrieve the position (X,Y) of an HTML element)
Get first elements height and width (e.g. marco gomes answer)
Get fourth element's x,y cordinates
Calculate:
Fourth's x pos minus (First's x pos + height) = empty space's height
As it is same width as other's width, you have a width.
If you need dynamically find gaps, you can loop all divs and put them in column groups (with help of x pos). Then you do above for each group's current and next in order element (they should be in right order). If the vertical difference is above set rule, you can assume you have a gap.
I’m new to jQuery/JavaScript but I have a solid idea of what I want, I’m just struggling to get it working.
I have a web page made up of different ‘div’s’ which have different ‘id’s’. I wrapped these divs in a pageContainer div. I want to be able to type a word in my ‘search bar’ and the word be looked for in the web page. It would signify a matching word by a collapsable div that would appear under the search bar which would have links to the different div id’s for where that word is. When clicked that word would be highlighted.
It’s simple but I figure it’s a good exercise to do.
Right now I know that I’m searching for the word in my pageContainer. As my understanding goes, I must search instead in each div, instead of the whole page. How can I do this?
Also as a side note, why is it that for every character I type, the search starts. Shouldn’t it only start on 3+ characters? I thought that’s what keyup does.
As of now, when I type in a word and search it, nothing happens on the web page.
/*Need to get the below search code working...*/
var thePage = $(".pageContainer");
// var content = $.makeArray(thePage.map(function(k, v){
// return $(v).text().toLowerCase();
// }));
$("#search").keyup(function(){
var input = $(this).val();
console.log(input);
//if match found, make corresponding div link appear in open collapsible div,
// else say nothing found in open collapsible div
// console.log(
thePage.filter.(function(index, value){
var foundText = $(this).val().toLowerCase();
// console.log(foundText, " BAAAAA");
console.log(index, value, " Second Here");//find 'user' input in value
// console.log(foundText.indexOf(input) >= 0);
console.log($(value).find(foundText.indexOf(input) >= 0));
// $(value).filter(foundText.indexOf(input) >= 0);
$(value).find(foundText.indexOf(input) >= 0);
var highlight = '<span class="word">' + value + '</span>';
});
// );
});
Interesting task, to sum it up the requirements are:
A web page made up of different ‘div’s’ which have different ‘id’s’.
These divs wrapped in a pageContainer div.
Type a word in my ‘search bar’ and the word be looked for in the web
page.
Signify a matching word by a collapsable div that would appear
under the search bar which would have links to the different div id’s
for where that word is.
When clicked that word would be highlighted.
Search should start on 3+ characters
I took all the above into consideration and created this codepen demo
(search for 'elementum' for example).
P.S. The highlight function is quite basic, it would be much better and safier to rely on a plugin like these.
var thePage = $(".pageContainer");
$('#results').hide(); //Hide the results div at first
$("#search").keyup(function() {
//Empty and hide the results div everytime the user types something
$('#results').empty();
$('#results').hide();
//Get the typed value
var input = $(this).val();
//Do nothing if it's smaller than three characters
if (input.length < 3) return;
//iterate through the results
var results = $(".pageContainer>div:contains('" + input + "')");
var counter = 0;
results.each(function(index, value) {
counter++;
//Get the current div that contains the given text
currentId = $(this).attr('id');
console.log('div' + index + ':' + currentId);
//Create a new element in the search div below the search input
var newP = $('<p/>', {
text: currentId
}).click(function() {
//Highlight when click
highliter(input, $(this).text());
});
$('#results').append(newP);
});
//Collapse if no results found
if (counter) $('#results').show();
else $('#results').hide();
});
function highliter(word, id) {
//Remove whatever was already highlighted
$('*').removeClass('highlight');
//Create a regular expression for the given word
var rgxp = new RegExp(word, 'g');
//Replace the plain text with a highlighted one
var repl = '<span class="highlight">' + word + '</span>';
var element = document.getElementById(id);
element.innerHTML = element.innerHTML.replace(rgxp, repl);
//Scroll to the position of the results
$('html, body').scrollTop($(".highlight").offset().top);
}
body{
background-color:grey;
}
#search{
width:200px;
}
#results{
width:200px;
border:2px solid black;
border-bottom-left-radius: 1em;
border-bottom-right-radius: 1em;
}
#results p{
background-color:#AAA;
margin: 8px;
cursor:pointer;
}
.highlight{
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text" />
<div id="results"></div>
<hr/>
<div class="pageContainer" id="main">
SECTION_1 (first div)
<div id="section1">
<p>Mauris eget risus ipsum. Ut dignissim justo id orci efficitur, ac ultricies sem ultricies. Nullam id velit vestibulum arcu eleifend tempor non nec purus. Sed mollis metus non aliquam accumsan. Fusce venenatis urna vel elit aliquet accumsan sit amet
et velit. Cras et molestie sem, et dignissim lorem. Etiam laoreet, dui eget cursus blandit, erat nisi pulvinar erat, sed volutpat turpis ante et massa. Nunc ornare orci ut purus maximus fermentum. Fusce nisl quam, maximus nec tortor quis, sagittis
maximus velit. Morbi in enim ac augue pharetra ultricies. Ut aliquet magna tellus, non volutpat ex vulputate ac. Curabitur in enim maximus, volutpat nibh ac, auctor urna.</p>
<p>Vivamus ac lacus rutrum, suscipit mauris et, rhoncus magna. Phasellus a ante a mi fringilla interdum sed feugiat massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec bibendum, tellus sed lobortis ullamcorper, nibh ex maximus
lacus, egestas scelerisque diam turpis a elit. Suspendisse iaculis, massa in ultricies sollicitudin, est dui bibendum augue, non dignissim nulla nibh ut dolor. Maecenas et mollis est. Donec condimentum laoreet erat, id maximus ante imperdiet in.
Proin id purus nulla. Vivamus tincidunt facilisis nisl, eget placerat elit mattis at. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
SECTION_2(second div)
<div id="section2">
<p>Fusce sit amet sem eget elit volutpat consequat. Nulla hendrerit sem dictum volutpat convallis. Sed interdum, arcu non facilisis condimentum, ipsum purus bibendum ex, a tincidunt leo leo vel sem. Maecenas porttitor quam non tortor accumsan interdum.
In id ultrices enim. Maecenas risus arcu, egestas nec ante et, vehicula bibendum dui. Quisque nec hendrerit ante. Integer in faucibus augue. Integer imperdiet felis id tempor facilisis. Nam lobortis sem non purus luctus varius. Quisque sit amet
justo ac dui convallis efficitur eget ut mi. Sed in efficitur nisi, ac rutrum mi. In pulvinar egestas turpis, non tincidunt orci finibus nec. Sed euismod augue eu tortor pharetra maximus eget at urna. Nulla efficitur elit lacus, sit amet faucibus
justo tristique eget.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pellentesque augue non aliquam scelerisque. In tincidunt vel nisi id porttitor. Integer vulputate cursus augue. Sed luctus accumsan dui elementum eleifend. Proin convallis, sem non
accumsan pulvinar, justo lorem mattis enim, nec lobortis libero nibh nec nisi. Nulla faucibus tellus in magna rutrum, sed porttitor orci pharetra. Mauris sit amet quam enim. Sed laoreet, neque in pretium congue, neque sem tincidunt massa, sed sollicitudin
orci ex eget nisl. Donec ultrices ligula eget augue convallis, vitae sagittis mauris vulputate. Nulla non bibendum odio, a tincidunt massa. Mauris ultricies augue sit amet venenatis ornare. In pellentesque quam vitae orci pretium rutrum. Vivamus
non orci congue orci pellentesque euismod ac id dolor. Nam accumsan scelerisque sodales.</p>
</div>
SECTION_3 (third div)
<div id="section3">
<p>Ut vel eros sit amet eros accumsan imperdiet. Donec placerat urna sit amet tellus eleifend rhoncus. Pellentesque finibus dolor tortor, et dignissim tellus iaculis eu. Etiam sollicitudin mattis fermentum. Etiam porta est turpis, ut consectetur lorem
sodales eu. Aenean rutrum volutpat efficitur. Morbi a elementum lectus, id ornare orci. Fusce bibendum dignissim lacinia. Aliquam venenatis urna et leo pretium tempus. Proin ligula felis, posuere nec vestibulum quis, pellentesque ut quam. Vestibulum
sed elementum lectus. Quisque at ipsum id lacus efficitur lacinia non in lorem. Donec tristique lectus eu ex laoreet, non tristique libero blandit. Curabitur massa quam, fermentum sit amet dui non, bibendum convallis orci. Sed vulputate turpis nec
erat commodo, rhoncus cursus quam ornare. Donec pellentesque posuere tortor vel efficitur.
<p>
<p>Duis ligula purus, vulputate sed sodales quis, condimentum sit amet arcu. Sed fermentum ut dui ac posuere. Donec tristique volutpat lobortis. Aenean tortor elit, molestie nec tincidunt non, semper vel nisi. Phasellus quis est sit amet massa facilisis
posuere. Integer sit amet elit semper ipsum sodales tempus vitae id lacus. Donec facilisis libero sit amet aliquam fermentum. Sed luctus, tortor et ullamcorper faucibus, libero sem ornare tortor, at gravida erat lorem elementum eros.</p>
</div>
</div>