javascript - Select sibling & parent with Cheerio -
i've been unable access simple pieces of html using cheerio, finished opening object $(this)
object , tracking down need. error occurs when there no object in stack, sibling or child. what's correct way select previous sibling, it's name, href & content, parent's css.
var code = $('code.lang-javascript, code.lang-js') dataset.blocks = [] code.map(function (i, elm) { var block = {} block.prevsiblingtag = $(this).parent().prev()[0].children[0].name block.prevsiblinghref = $(this).parent().prev()[0].children[0].attribs.href block.prevsiblingcontent = $(this).parent().prev()[0].children[0].text() block.parenttag = $(this)[0].name block.parentclass = $(this)[0].attribs.class block.code = $(this).html() dataset.blocks.push(block) })
i doing , mess.
var $parent = $($(this).parent().html()) var $prevsibling = $($(this).parents().prev()) var block = {} block.parentclass = $parent.attr('class') block.prevsibling = $prevsibling.html() block.code = $(this).html()
the problem if there no children previous sibling $(this).parent().prev()[0]
null.
so better jquery obeject reference target element use attribute/property values like
var code = $('code.lang-javascript, code.lang-js') dataset.blocks = code.map(function (i, elm) { var block = {}, $this = $(this), target = $this.parent().prev().children().eq(0); block.prevsiblingtag = target.attr('name'); block.prevsiblinghref = target.attr('href'); block.prevsiblingcontent = target.text() block.parenttag = this.name block.parentclass = $this.attr('class') block.code = $this.html() return block; }).get();
also since using .map()
, can return array
Comments
Post a Comment