如何插入<a href=""> into a </a> <div> <a href=""> with JavaScript

时间:2018-01-05 16:05:43

标签: javascript html css

I'm pretty noob when is come to this. So, maybe for you, is piece of cake, but for me is like escalading the Everest. Please help me. Thank you!

I have this:

I have this:

</br> <a class="link" href="#"><b>A</b></a>
</br> <a class="link" href="B"><b>B</b></a>
</br> <a class="link" href="C"><b>C</b></a>
</br>.....I have hundreds of links


<hr> How to transform that, into this, with javascript:

<div>
  <a class="link" href="#"><b>A</b></a>
</div>
<div>
  <a class="link" href="#"><b>B</b></a>
</div>
<div>
  <a class="link" href="#"><b>C</b></a>
</div>

1 个答案:

答案 0 :(得分:1)

目前还不是很清楚你需要什么,但试试这个是否符合你的需要:

function insertIntoDivs() {
            //array with all anchors that have link as class
            var allLinks = document.getElementsByClassName("link");
            var arrayLinks = Array.from(allLinks);
            var quantLinks = arrayLinks.length;   
            //loop until all elements got hiw own div
            for (var i = 0; i < quantLinks; i++) {
                var anchor = arrayLinks[i];
                var containerDiv = document.createElement('div'); //create the div
                containerDiv.style.height = '25px';
                containerDiv.style.width = '60px';
                containerDiv.style.border = '1px solid black';
                containerDiv.appendChild(anchor); //add anchor to the div
                document.body.appendChild(containerDiv);
            }
        }
    <a class="link" href="#">A</a>
    <a class="link" href="#">B</a>
    <a class="link" href="#">C</a>
    <a class="link" href="#">D</a>
    <a class="link" href="#">E</a>
    <a class="link" href="#">F</a>
    <br />
    <input type="button" onclick="insertIntoDivs();" value="Insert Into Divs" />