CCCam
CCCam

Reputation: 85

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></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?

Upvotes: 1

Views: 991

Answers (3)

Johan Olsson
Johan Olsson

Reputation: 618

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;
        }
    }
});

Upvotes: 0

Eli
Eli

Reputation: 17825

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

Upvotes: 1

Ben Everard
Ben Everard

Reputation: 13804

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

Upvotes: 0

Related Questions