开发者

loop to get the href attr and put as a variable as text in html

I am getting myself confused with the DOM.

I have this HTML:

<div class="my-list">
    <div class="name"></div>
    <div class="title"><a href="some_url"></a></div>
</div>
<div class="my-list">
    <div class="name"></div>
    <div class="title"><a href="some_url"></a>&开发者_StackOverflow中文版lt;/div>
</div>

And this JavaScript:

var myList = $(".my-list");
for (var i=0;  i < myList.length; i++) {

    // what I want is at myList[i] to get the
    // $(".title a").attr("href") as a variable
    // and then put this variable as text
    // into the html of the $(".name") html

}

What is a good way to construct this?


$(".my-list").each(function() {
    var element = $(this);
    var href = element.find('.title a').attr('href');
    element.find('.name').text(href);
});


This should do it:

$('.my-list').each(function() {
    var self = $(this);
    $('.name',self).html( $('.title a', self).attr('href') );
});

Here's an example of it working


Im not much for jquery but this a sure way to do it

$(".my-list").each(function(item){
    var divs = item.getElementsByTagName('div');
    for(var i in divs){
        if(typeof divs[i] != 'undefined' && divs[i].className == 'name'){
        divs[i].innerHTML = item.getElementsByTagName('a')[0].href;
        }
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜