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? Commented 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. Commented 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. Commented Jan 26, 2012 at 9:46
  • Added how I'm selecting the links. And HTML before and after! Commented Jan 26, 2012 at 10:02
  • Maybe select everything until first <p> tag? Commented 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.