【JavaScript】特定HTML要素の更新を監視してStyle属性の特定プロパティを消すスクリプト

 last update 2023年12月15日

「JavaScript で HTML の特定要素の style 属性を監視して特定プロパティだけを消すコード」を自分用にメモしておきます。

(行儀の悪い)JS が動的に書く CSS のせいでレイアウトが崩れるケース、特に、親要素から CSS の Intrinsic 系サイジングでどうにもフィットできない、あるいはしずらいケースで使えるかも。

のっぴきならない事情で書いた褒められない実装ですが、案の定、他の方法で回避できたのでここに供養。

  • 仕様は #target-element > div:nth-of-type(2) > div 要素の style 属性を監視して、height プロパティがあったら消すだけ
  • MutationObserver で要素・属性の更新を検知。タイマでポーリングしない
  • 初回実行時は height プロパティを強制削除(初回分は更新検知されないので)
<script>
// Monitor and remove the height from the style attribute
// Target selector: div inside the 2nd div
const targetSelector = '#target-element > div:nth-of-type(2) > div';
const targetElement = document.querySelector(targetSelector);

// Callback function to monitor changes
const callback = (mutationsList, observer) => {
	for (let mutation of mutationsList) {
		if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
			const style = targetElement.getAttribute('style');

			// Check if the style attribute contains height
			if (style && style.toLowerCase().includes('height')) {
				// Remove the height property
				targetElement.style.removeProperty('height');
			}
		}
	}
};

// Create an instance of MutationObserver
const observer = new MutationObserver(callback);

// Start observing
observer.observe(targetElement, {
	attributes: true,		// Observe changes to attributes
	attributeFilter: ['style']	// Only observe changes to the style attribute
});

const style = targetElement.getAttribute('style');

// remove the height property
if (style && style.toLowerCase().includes('height')) {
	targetElement.style.removeProperty('height');
}
</script>Code language: JavaScript (javascript)

対象がアフター IE のモダンブラウザなら、このコードが役立つケースのほとんどは CSS だけで対処できそうなものですが。

でも、Style を消す以上のことをする時には参考になるかも。

Hatena Pocket Line

コメントを記入