How to find all links in a div, add them to the DOM and give a count of the links
I ha开发者_Go百科ve a list of links inside a div. I am trying to click a button outside of that div and have every link inside of the div printed on screen as well as the number of links on the page. Not quite sure how to do it..
js
$(function()
{
$('#button').click(function()
{
$('#links a').each(function()
{
var count = $('#links a').length;
$(this).appendTo('#results');
$('span').text('there are ' + count 'links');
});
});
});
html
<a href="#" id="button">button</a>
<div id="links">
<a href="#">one</a>
<a href="#">two</a>
<a href="#">three</a>
</div>
<div id="results"></div>
this prints the number of links in the result div:
$('#button').click(function(){
var count = $('#links a').length;
$('#results').text('there are ' + count + ' links');
});
like this moves all links in to another div:
$('#button').click(function(){
var elements = $('#links a')
$('#results').append(element);
});
combined it would be (in correct order:)
$('#button').click(function(){
var count = $('#links a').length;
$('#results').text('there are ' + count + ' links');
var elements = $('#links a')
$('#results').append(element);
});
or:
$('#button').click(function(){
var elements = $('#links a'); //<-- grab all links
$('#results') //<-- select the target div
.text('there are ' + elements.length + ' links'); //<-- set count
$('#links2').append(elements) //<-- put links in another div
});
live test here
精彩评论