Home > Software design >  Filtering child html element from parent
Filtering child html element from parent

Time:01-08

I'm trying to get the inner element of the container with .filter(). But it return undefined until searching it within parent element with .find(); How can I search it directly with .filter() only without the need to use .find() ?

So the output will like this : <p >This Paragraph Contents</p>

$(document).ready(() => {
  let $htmlEl = `
                <body>
                    <div >
                       <div >
                           <p >This Paragraph Contents</p>
                       </div>
                    </div>
                </body>
            `;
  let $res = $($htmlEl);
  let $parentHtml = $res.filter('.container').html();
  let $childHtml = $res.filter('.body-content').html();
  // alert($res.filter('.container').find('.body-content').html());
  // alert($parentHtml);
  console.log($childHtml);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

CodePudding user response:

Filter works on a selection

Instead you can use a selector and scope it, I guess that is the same as find, but why is find not allowed?

$(document).ready(() => {
  let $htmlEl = `<body>
    <div >
      <div >
        <p >This Paragraph Contents</p>
      </div>
    </div>
  </body>`;
  
  let $res = $($htmlEl);
  $("body").append($res)
  let $childHtml = $('.body-content',$res).html().trim()
  console.log($childHtml);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

  •  Tags:  
  • Related