Home > front end >  Select element inside jquery
Select element inside jquery

Time:06-02

I was making a vanilla javascript bar graph where I made the bar inside the li tag. In the code below, i use the attribute within the li tag to set the height of the bar, but when I try to select the bar from within the li tag. I am unable to do so.


<ul >
                        <li  bar-height="100">
                            <div ></div>
                            MON
                        </li>
                        <li  bar-height="190">
                            <div ></div>
                            TUES
                        </li>
                        <li  bar-height="260">
                            <div ></div>
                            WED
                        </li>
                        <li  bar-height="180">
                            <div ></div>
                            THURS
                        </li>
                        <li  bar-height="220">
                            <div ></div>
                            FRI
                        </li>
                        <li  bar-height="300">
                            <div ></div>
                            SAT
                        </li>
                        <li bar-height="50">
                            <div ></div>
                            SUN
                        </li>
                    </ul>


//JAVASCRIPT


var children=$('.GraphWrapper').children();
for(var i=0;i<children.length;i  ){

    let hgt = children[i].getAttribute('bar-height');

    bar = children[i] > $('.bar');

    bar.css('height',hgt 'px');
}

CodePudding user response:

Here is what you need:

var children = $('.GraphWrapper').children();
for (var i = 0; i < children.length; i  ) {
    let kid=$(children[i]);
    let hgt=kid.attr('bar-height');
    let bar=kid.find(".bar");
    bar.css('height', hgt   'px');
}

Because the children() function return a list of DOM object, so you need to convert the children[i] to jQuery object, and then use the find method to find all divs in the li element, finally, change the height of the div as you want.

  • Related