Tomage
Tomage

Reputation: 187

How to change nested child's class and return the original parent with jQuery?

I have a piece of html template in a string which I need to update. Say:

var tpl = "<div><a href="#"><img src="..."></a></div>";

How do I add a class to the a tag and return back the updated string? This string template can be entirely customized so the code must not rely on this particular string.

If I do: $(tpl).find('a').addClass('myClass') then the original tpl variable will not be affected.

If I do: tpl = $(tpl).find('a').addClass('myClass').html() then I will only get the contents of a tag.

So what would be the correct approach?

The contents of tpl should in the end be:

<div><a href="#" class="myClass"><img src="..."></a></div>

Upvotes: 1

Views: 122

Answers (3)

Neel Gala
Neel Gala

Reputation: 2400

If you have no "a-href tag previously", then you can use :-

tpl = $(tpl).find('a').eq(0).addClass('myClass');

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

You can use $.fn.end() to return original matched set:

tpl = $(tpl).find('a').addClass('myClass').end().prop('outerHTML');

var tpl = '<div><a href="#"><img src="..."></a></div>';
tpl = $(tpl).find('a').addClass('myClass').end().prop('outerHTML');
console.log(tpl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

And if you want to return the parent jq object, not the outer HTML string, remove prop():

tpl = $(tpl).find('a').addClass('myClass').end();

Upvotes: 3

Antony Thompson
Antony Thompson

Reputation: 1638

You can wrap your template around a div and go back to it after your modifications.

$(function() {
  var tmpl = '<div><a href="#"><img src="#"></a></div>';
  tmpl = jQuery("<div class=\"outer\">")
  .append(tmpl)
  .find('a')
  .addClass('test')
  .parents('.outer')
  .html();
  alert(tmpl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

https://jsfiddle.net/5qnLh13b/7/

Upvotes: 0

Related Questions