I am trying to traverse a dynamically generated page, grabbing specific span ID an then append that id inside an href to the previous span. Currently this generates BOTH links inside each h2.classA instead of the respective single link in each instance. Should I be assigning the each() to the h2 instead? Any help is greatly appreciated.
Existing HTML
<h2>
<span class="classA"> </span>
<span class="classB" id="somename"> SomeName </span>
</h2>
<h2>
<span class="classA"> </span>
<span class="classB" id="anothername"> SomeName </span>
</h2>
Attempt:
$("h2 span.classB").each(function() {
var content = $(this).attr('id');
$('h2 span.classA').append('<a href="index.php?title='+content+'"> edit me </a>');
});
Desired HTML result
<h2>
<span class="classA"><a href="index.php?title='+somename+'"> LINK1 </a></span>
<span class="classB" id="somename"> SomeName </span>
</h2>
<h2>
<span class="classA"><a href="index.php?title='+anothername+'"> LINK2 </a></span>
<span class="classB" id="anothername"> AnotherName </span>
</h2>
You are appending the anchors to all the
classAelements in each iteration, for selecting the previous span element, you can use theprevmethod:http://jsfiddle.net/c7V9z/