diff --git a/src/__fixtures__/fixtures.ts b/src/__fixtures__/fixtures.ts index f1b7c147ad..d649667f24 100644 --- a/src/__fixtures__/fixtures.ts +++ b/src/__fixtures__/fixtures.ts @@ -115,4 +115,14 @@ export const noscript = [ '', ].join(''); +export const script = [ + '
', + 'A', + '', + 'B', + '
', +].join(''); + export const mixedText = '1TEXT2'; diff --git a/src/api/attributes.spec.ts b/src/api/attributes.spec.ts index 2b5e43d3b6..b0ecfddb89 100644 --- a/src/api/attributes.spec.ts +++ b/src/api/attributes.spec.ts @@ -2,6 +2,7 @@ import cheerio from '..'; import type { Cheerio } from '../cheerio'; import type { Element } from 'domhandler'; import { + script, fruits, vegetables, food, @@ -296,6 +297,22 @@ describe('$(...)', () => { expect($a.prop('innerHTML')).toBe(''); }); + it('("textContent") : should render properly', () => { + expect(selectMenu.children().prop('textContent')).toBe( + 'Option not selected' + ); + + expect($(script).prop('textContent')).toBe('A var foo = "bar";B'); + }); + + it('("innerText") : should render properly', () => { + expect(selectMenu.children().prop('innerText')).toBe( + 'Option not selected' + ); + + expect($(script).prop('innerText')).toBe('AB'); + }); + it('(inherited properties) : prop should support inherited properties', () => { expect(selectMenu.prop('childNodes')).toBe(selectMenu[0].childNodes); }); diff --git a/src/api/attributes.ts b/src/api/attributes.ts index 80223d83ef..783f6862ad 100644 --- a/src/api/attributes.ts +++ b/src/api/attributes.ts @@ -8,6 +8,7 @@ import { text } from '../static'; import { isTag, domEach, camelCase, cssCase } from '../utils'; import type { Node, Element } from 'domhandler'; import type { Cheerio } from '../cheerio'; +import { innerText, textContent } from 'domutils'; const hasOwn = Object.prototype.hasOwnProperty; const rspace = /\s+/; const dataAttrPrefix = 'data-'; @@ -300,7 +301,7 @@ export function prop( ): T extends Element ? string : undefined; export function prop( this: Cheerio, - name: 'innerHTML' | 'outerHTML' + name: 'innerHTML' | 'outerHTML' | 'innerText' | 'textContent' ): string | null; export function prop( this: Cheerio, @@ -361,6 +362,12 @@ export function prop( return isTag(el) ? el.name.toUpperCase() : undefined; } + case 'innerText': + return innerText(this[0]); + + case 'textContent': + return textContent(this[0]); + case 'outerHTML': return this.clone().wrap('').parent().html();