0

I have a li element that I want to transform to a link. I have a script below that identifies the text - from here I want to make it a link instead. I want to use the string as a value in the link.

The label looks like this:

<li><label>Spårningsnummer</label>JVGL123456789</li>

And I want to append a link inside the label or replace the label with an a element with a link that looks like this:

http://www.dhl.se/sv/express/godssoekning.html?AWB=JVGL123456789&brand=DHL

Where this number is dynamic:

JVGL123456789

Script so far:

<li><label>Spårningsnummer</label>JVGL123456789</li>

if ($('fieldset li:contains("JVGL")').length > 0) {

}

I understand how to append pr replace the element with a static link - but how do I get the value from the string in my link?

1 Answer 1

2

Use contents() and filter() with condition nodeType == 3 to get the text node, then wrap it with an anchor tag using wrap().

$('li:contains("JVGL")').each(function() {
  $text = $(this).contents().filter(function() {
    return this.nodeType == 3;
  });
  text = $text.text();
  $text.wrap('<a href="http://www.dhl.se/sv/express/godssoekning.html?AWB=' + text +  '&brand=DHL" ></a>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<li>
    <label>Spårningsnummer</label>JVGL123456789
</li>

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

1 Comment

That worked really good! And it looks so easy - very nice script. This will be bookmarked and studied, thanks again!

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.