MCPcopy Index your code
hub / github.com/getsentry/sentry-javascript / _htmlElementAsString

Function _htmlElementAsString

packages/core/src/utils/browser.ts:71–130  ·  view source on GitHub ↗

* Returns a simple, query-selector representation of a DOM element * e.g. [HTMLElement] => input#foo.btn[name=baz] * @returns generated DOM path

(el: unknown, keyAttrs?: string[])

Source from the content-addressed store, hash-verified

69 * @returns generated DOM path
70 */
71function _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {
72 const elem = el as {
73 tagName?: string;
74 id?: string;
75 className?: string;
76 getAttribute(key: string): string;
77 };
78
79 const out = [];
80
81 if (!elem?.tagName) {
82 return '';
83 }
84
85 // @ts-expect-error WINDOW has HTMLElement
86 if (WINDOW.HTMLElement) {
87 // If using the component name annotation plugin, this value may be available on the DOM node
88 if (elem instanceof HTMLElement && elem.dataset) {
89 if (elem.dataset['sentryComponent']) {
90 return elem.dataset['sentryComponent'];
91 }
92 if (elem.dataset['sentryElement']) {
93 return elem.dataset['sentryElement'];
94 }
95 }
96 }
97
98 out.push(elem.tagName.toLowerCase());
99
100 // Pairs of attribute keys defined in `serializeAttribute` and their values on element.
101 const keyAttrPairs = keyAttrs?.length
102 ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])
103 : null;
104
105 if (keyAttrPairs?.length) {
106 keyAttrPairs.forEach(keyAttrPair => {
107 out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
108 });
109 } else {
110 if (elem.id) {
111 out.push(`#${elem.id}`);
112 }
113
114 const className = elem.className;
115 if (className && isString(className)) {
116 const classes = className.split(/\s+/);
117 for (const c of classes) {
118 out.push(`.${c}`);
119 }
120 }
121 }
122 for (const k of ['aria-label', 'type', 'name', 'title', 'alt']) {
123 const attr = elem.getAttribute(k);
124 if (attr) {
125 out.push(`[${k}="${attr}"]`);
126 }
127 }
128

Callers 1

htmlTreeAsStringFunction · 0.70

Calls 3

isStringFunction · 0.90
pushMethod · 0.80
forEachMethod · 0.65

Tested by

no test coverage detected