2

I have this HTML

<div class="box">
    <a href="#goals"> | <a href="#rules"> | <a href="#controls">
    <p><a name="goals"></a></p>
    <h2>Goals</h2>
    ... yada yada

and want it like this.

<div id="nav">
    <a href="#goals"> | <a href="#rules"> | <a href="#controls">
</div>

JQuery have wrapAll(), but I can only select the links so the "|" gets left outside the div.

before('div') and after('div') creates a closed element, like <div></div> so what to do?

I'm using

$('.box a[href^="#"]')

to select the links. They are part of a text resource file, so I cant edit anything.

5
  • Why would one want to add unclosed HTML tags?
    – Stefan
    Jan 26, 2012 at 9:44
  • he doesn't, but he needs to wrap some content and jQuery won't let you add the opening and closing tags separately.
    – Alnitak
    Jan 26, 2012 at 9:45
  • how are you currently trying to "select" the desired nodes? Please also show the markup immediately before and after the set of nodes you want wrapped.
    – Alnitak
    Jan 26, 2012 at 9:46
  • Added how I'm selecting the links. And HTML before and after!
    – heffaklump
    Jan 26, 2012 at 10:02
  • Maybe select everything until first <p> tag?
    – heffaklump
    Jan 26, 2012 at 10:05

1 Answer 1

1

Given valid markup as input, this works:

// find first link - using jQuery for expedience here
var a = $('.box > a')[0];

// create new div, and insert it before the link
var d = document.createElement('div');
d.id = 'nav';
a.parentNode.insertBefore(d, a);

// for each following node, reparent it inside the div
while (a && a.tagName !== 'P') {
    var n = a.nextSibling;
    d.appendChild(a);
    a = n;
};

It's actually easier without jQuery, because jQuery provides no easy way to obtain the text nodes that are contained within your menu.

Working demo at http://jsfiddle.net/HpgJV/3/

To fix your incorrect HTML input, try this:

$('.box a[href^="#"]').each(function() {
    $(this).contents().insertAfter(this);
});

which will move any text nodes that are dropped inside the <a> tags because of the invalid markup so that they're after the tag instead.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.