2

I have an anchor with class .anchor in my page.

Now what i want to do is that I want to add .anchor element in html like :

var html='';
var html += '<header><ul><li>' + $('.anchor ').get(0) + '</li></ul></header>';

this should produce below html...

<header><ul><li><a href="any url" attribute="value" attribute1="value1" class="anchor ">inner text / html</a></li></ul></header>

I am using this, becoause I dont want to use append/prepend etc again and again. I will use approprite jquery function at the end. So I am using adding content in string. But it is not working. Please suggest.

3
  • you are asking questions about html and not even showing us your html? Commented Dec 15, 2014 at 10:24
  • 1
    $('.anchor ').text() Commented Dec 15, 2014 at 10:24
  • it will add only text but not href, classes, attributes with <a> tag. Commented Dec 15, 2014 at 10:33

2 Answers 2

4

You want the outerHTML of your anchor, which you can use JavaScript to get:

Also, you're re-declaring your html variable, don't do that

var html='';
html += '<header><ul><li>' + $('.anchor ')[0].outerHTML + '</li></ul></header>'

If you have more than one anchor, you can do something like this instead:

var html = "<header><ul>";

$(".anchor").each(function () {
    html += "<li>" + this.outerHTML + "</li>";
});

html += "</ul></header>
Sign up to request clarification or add additional context in comments.

2 Comments

outerHTML is not working if I am using $('.element').find('.anchorclass').outerHTML. I have only 1 element.
@ShyamBabuKushwaha Then you need to use $('element').find('anchorclass')[0].outerHTML, note the use of [0] which refers to the JavaScript object, not the jQuery object.
0

If you have a simple <a> tag, you can do a simple copy:

var html = '';
var $a = $('.anchor');
html += '<header><ul><li><a href="' + $a.get(0).href + '">' + $a.html() + '</a></li></ul></header>';

http://jsfiddle.net/9fhkuh4w/3/

Otherwise, do a deep copy of the DOM element (the anchor) using jQuery clone():

var html = '';
var $destination = $('#here');
for (var i = 0; i < 5; i++) {
    var $a = $('.anchor').first().clone();
    $destination.append($a);
}

http://jsfiddle.net/9fhkuh4w/5/

3 Comments

What if I have many attributes in <a>? It is same as I am hardcoding instead of using existing element.
if you want to copy exactly the same dom element, use jquery clone()
@ShyamBabuKushwaha i updated the answer with a fiddle using clone()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.