I want to manipulate some HTML that I have no direct control over.
There are two elements that I could target with JavaScript, and then some ... well, sort of floating text between them.
<div id="anOuterDiv">
<div class="variousOtherElements">blah can contain dashes - oh yes it can</div>
<div class="someOtherElements">blah can contain dashes - oh yes it can</div>
<span class="branch">Some City Public Library</span> - <span class="location">Story Room</span>
</div>
Basically, I just need to remove or hide span.branch and span.location ... AND the dash between them. Right now I'm hiding the two spans via CSS, and the dash is just floating out there ...
The content of all elements can vary. There can be dashes in the other elements.
Either a jQuery or pure JavaScript solution would be useful. I have not been able to figure out a way to target this dash that is just hanging out there. I need to hide it and have it not take up space.
You could wrap the elements with branch and location classes in a new div (container of their own), along with any siblings in between. You can then hide or remove them as desired:
$(document).ready(function() {
$('.branch').each(function() {
var to_wrap = [this];
var _sib = this;
var _continue = true;
while (_continue && (_sib = _sib.nextSibling) && (_sib.className === undefined || _sib.className == 'location')) {
to_wrap[to_wrap.length] = _sib;
if (_sib.className == 'location')
_continue = false;
}
buildHiddenDivRow(to_wrap, $(this).parent());
});
});
function buildHiddenDivRow(arr, $parentElement) {
$('<div />', {
'class': 'branch-location',
'style': 'display:none'
}).prepend(arr).appendTo($parentElement);
}
I didn't give the algorithm much thought, but I did clean it up some. I'm sure there is plenty of room for optimization and making it more concise and/or readable.
class="location span"
), or there is no element that has a location class, this will result in an infinite-loop and hang the browser.For these reasons and more, use this as a reference and not production-ready code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments