简体   繁体   中英

Using values of multiple divs javascript

I have multiple divs on the site! for example

<div id='id_111232'>Some text</div>
<div id='id_111233'>Some text</div>
<div id='id_111234'>Some text</div>
<div id='id_111235'>Some text</div>

And i want to create a javascript that is appending in to this div like this

<a href='http://something.com/some/xx'></a>

where xx is the value of the above mentioned divs so i mean: id_ value How could I do this?

Try this - http://jsfiddle.net/9DAd7/2

var divs = document.getElementsByTagName("div");
var size = divs.length;

for ( var i = 0; i < size; i++ ) {
    var link = document.createElement("a");
    var id = divs[i].getAttribute("id").replace("id_", "");

    link.innerHTML = id;
    link.href      = "http://www.example.com/" + id;

    divs[i].appendChild(link);
}

Or even easier with jQuery - http://jsfiddle.net/9DAd7/3/

$("div").each(function() {
    var id = $(this).attr("id").replace("id_", "");
    $(this).append( '<a href="http://www.example.com/' + id + '">' + id + '</a>' );
});

Not sure if I clearly understand what you are trying to accomplish but if you were wanting to append each of the texts from the above divs onto the end of the href you could do something JQuery like below.

<a id="myLink" href='http://something.com/some'></a>

<div id='appendedDivs'>
<div id='id_111232'>Some text</div>
<div id='id_111233'>Some text</div>
<div id='id_111234'>Some text</div>
<div id='id_111235'>Some text</div>
</div>

<script type="text/javascript">
    var appendedLink=$("myLink").attr("href")+'/';
        $('appendedDivs').childen().each( function() {
        appendedLink = appendedLink + this.text();
    });

    $("myLink").attr("href")=appendedLink;

</script>

this would go through and append all the divs texts inside appendedDivs to your url.

Good Luck!

With jQuery you can loop through the divs by a meaningful selector, parse the id attribute and create a link like this:

HTML:

<div class="link" id='id_111232'>Some text</div>
<div class="link" id='id_111233'>Some text</div>
<div class="link" id='id_111234'>Some text</div>
<div class="link" id='id_111235'>Some text</div>

Javascript:

$('div.link').each(function() {
    var id = $(this).attr('id').split('_')[1];
    $(this).html('<a href="http://something.com/some/' + id + '">' + $(this).text() + '</a>');
});​

Here is the working fiddle: http://jsfiddle.net/archatas/uPR62/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM