Search code examples
javascriptjqueryappendwidth

javascript append div and set its width same as an anchor text


I'm trying to create a div programmatically, append it to a parent div, and set this newly created div's width equal to the text's width present inside a <a>...</a>, child of the same parent div (its brother).

html:

<div id='div0'>
 <a href="#">text</a>
</div>

js/jquery:

        var curDiv = document.getElementById('div0');
        var iDiv = document.createElement('div');
        iDiv.id = 'newDivId';
        iDiv.className = 'newDivClass';
        curDiv.appendChild(iDiv);

        // the div is appended successfuly
        // next step below doesn't work

        var curTxt = $('#div0').next("a").text();
        var curWidth = curTxt.width();

        $('.newDivClass').css('width', curWidth);

What i get using .log is that variable curTxt = (empty), and it also returns this error: curTxt.width is not a function.


Solution

  • you can do this

    var curDiv = document.getElementById('div0');
    var iDiv = document.createElement('div');
    iDiv.id = 'newDivId';
    iDiv.className = 'newDivClass';
    iDiv.style.background = "red"
    iDiv.style.height = "10px"
    curDiv.appendChild(iDiv);
    
    // the div is appended successfuly
    // next step below doesn't work
    
    var curWidth = $('#div0 > a').width();
    
    console.log(curWidth)
    
    
    $('.newDivClass').css('width', curWidth);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='div0'>
     <a href="#">text</a>
    </div>

    your main problem is next() seem to search for a sibling while the link is a child