2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Peter Kelly (pmk@post.com)
5 * (C) 2001 Dirk Mueller (mueller@kde.org)
6 * (C) 2007 David Smith (catfish.man@gmail.com)
7 * Copyright (C) 2004-2014 Apple Inc. All rights reserved.
8 * (C) 2007 Eric Seidel (eric@webkit.org)
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
29 #include "AXObjectCache.h"
31 #include "CSSParser.h"
33 #include "ChromeClient.h"
34 #include "ClientRect.h"
35 #include "ClientRectList.h"
36 #include "ContainerNodeAlgorithms.h"
37 #include "DOMTokenList.h"
38 #include "DocumentSharedObjectPool.h"
39 #include "ElementIterator.h"
40 #include "ElementRareData.h"
41 #include "EventDispatcher.h"
42 #include "EventHandler.h"
43 #include "FlowThreadController.h"
44 #include "FocusController.h"
45 #include "FocusEvent.h"
46 #include "FrameSelection.h"
47 #include "FrameView.h"
48 #include "HTMLCanvasElement.h"
49 #include "HTMLCollection.h"
50 #include "HTMLDocument.h"
51 #include "HTMLFormControlsCollection.h"
52 #include "HTMLLabelElement.h"
53 #include "HTMLNameCollection.h"
54 #include "HTMLOptionsCollection.h"
55 #include "HTMLParserIdioms.h"
56 #include "HTMLSelectElement.h"
57 #include "HTMLTableRowsCollection.h"
58 #include "HTMLTemplateElement.h"
59 #include "InsertionPoint.h"
60 #include "KeyboardEvent.h"
61 #include "MutationObserverInterestGroup.h"
62 #include "MutationRecord.h"
63 #include "NodeRenderStyle.h"
64 #include "PlatformWheelEvent.h"
65 #include "PointerLockController.h"
66 #include "RenderLayer.h"
67 #include "RenderNamedFlowFragment.h"
68 #include "RenderRegion.h"
69 #include "RenderTheme.h"
70 #include "RenderView.h"
71 #include "RenderWidget.h"
72 #include "SVGDocumentExtensions.h"
73 #include "SVGElement.h"
75 #include "SelectorQuery.h"
77 #include "StyleProperties.h"
78 #include "StyleResolver.h"
79 #include "TextIterator.h"
80 #include "VoidCallback.h"
81 #include "WheelEvent.h"
82 #include "XLinkNames.h"
83 #include "XMLNSNames.h"
85 #include "htmlediting.h"
87 #include <wtf/BitVector.h>
88 #include <wtf/CurrentTime.h>
89 #include <wtf/text/CString.h>
93 using namespace HTMLNames;
94 using namespace XMLNames;
96 static inline bool shouldIgnoreAttributeCase(const Element& element)
98 return element.isHTMLElement() && element.document().isHTMLDocument();
101 static HashMap<Element*, Vector<RefPtr<Attr>>>& attrNodeListMap()
103 static NeverDestroyed<HashMap<Element*, Vector<RefPtr<Attr>>>> map;
107 static Vector<RefPtr<Attr>>* attrNodeListForElement(Element& element)
109 if (!element.hasSyntheticAttrChildNodes())
111 ASSERT(attrNodeListMap().contains(&element));
112 return &attrNodeListMap().find(&element)->value;
115 static Vector<RefPtr<Attr>>& ensureAttrNodeListForElement(Element& element)
117 if (element.hasSyntheticAttrChildNodes()) {
118 ASSERT(attrNodeListMap().contains(&element));
119 return attrNodeListMap().find(&element)->value;
121 ASSERT(!attrNodeListMap().contains(&element));
122 element.setHasSyntheticAttrChildNodes(true);
123 return attrNodeListMap().add(&element, Vector<RefPtr<Attr>>()).iterator->value;
126 static void removeAttrNodeListForElement(Element& element)
128 ASSERT(element.hasSyntheticAttrChildNodes());
129 ASSERT(attrNodeListMap().contains(&element));
130 attrNodeListMap().remove(&element);
131 element.setHasSyntheticAttrChildNodes(false);
134 static Attr* findAttrNodeInList(Vector<RefPtr<Attr>>& attrNodeList, const QualifiedName& name)
136 for (auto& node : attrNodeList) {
137 if (node->qualifiedName().matches(name))
143 static Attr* findAttrNodeInList(Vector<RefPtr<Attr>>& attrNodeList, const AtomicString& localName, bool shouldIgnoreAttributeCase)
145 const AtomicString& caseAdjustedName = shouldIgnoreAttributeCase ? localName.convertToASCIILowercase() : localName;
146 for (auto& node : attrNodeList) {
147 if (node->qualifiedName().localName() == caseAdjustedName)
153 Ref<Element> Element::create(const QualifiedName& tagName, Document& document)
155 return adoptRef(*new Element(tagName, document, CreateElement));
158 Element::Element(const QualifiedName& tagName, Document& document, ConstructionType type)
159 : ContainerNode(document, type)
167 if (document().hasLivingRenderTree()) {
168 // When the document is not destroyed, an element that was part of a named flow
169 // content nodes should have been removed from the content nodes collection
170 // and the isNamedFlowContentNode flag reset.
171 ASSERT_WITH_SECURITY_IMPLICATION(!isNamedFlowContentNode());
175 ASSERT(!beforePseudoElement());
176 ASSERT(!afterPseudoElement());
180 if (hasSyntheticAttrChildNodes())
181 detachAllAttrNodesFromElement();
183 if (hasPendingResources()) {
184 document().accessSVGExtensions().removeElementFromPendingResources(this);
185 ASSERT(!hasPendingResources());
189 inline ElementRareData* Element::elementRareData() const
191 ASSERT_WITH_SECURITY_IMPLICATION(hasRareData());
192 return static_cast<ElementRareData*>(rareData());
195 inline ElementRareData& Element::ensureElementRareData()
197 return static_cast<ElementRareData&>(ensureRareData());
200 void Element::clearTabIndexExplicitlyIfNeeded()
203 elementRareData()->clearTabIndexExplicitly();
206 void Element::setTabIndexExplicitly(short tabIndex)
208 ensureElementRareData().setTabIndexExplicitly(tabIndex);
211 bool Element::supportsFocus() const
213 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
216 Element* Element::focusDelegate()
221 short Element::tabIndex() const
223 return hasRareData() ? elementRareData()->tabIndex() : 0;
226 void Element::setTabIndex(int value)
228 setIntegralAttribute(tabindexAttr, value);
231 bool Element::isKeyboardFocusable(KeyboardEvent*) const
233 return isFocusable() && tabIndex() >= 0;
236 bool Element::isMouseFocusable() const
238 return isFocusable();
241 bool Element::shouldUseInputMethod()
243 return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::Update) != Editability::ReadOnly;
246 bool Element::dispatchMouseEvent(const PlatformMouseEvent& platformEvent, const AtomicString& eventType, int detail, Element* relatedTarget)
248 if (isDisabledFormControl())
251 RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventType, document().defaultView(), platformEvent, detail, relatedTarget);
253 if (mouseEvent->type().isEmpty())
254 return true; // Shouldn't happen.
256 ASSERT(!mouseEvent->target() || mouseEvent->target() != relatedTarget);
257 bool didNotSwallowEvent = dispatchEvent(mouseEvent) && !mouseEvent->defaultHandled();
259 if (mouseEvent->type() == eventNames().clickEvent && mouseEvent->detail() == 2) {
260 // Special case: If it's a double click event, we also send the dblclick event. This is not part
261 // of the DOM specs, but is used for compatibility with the ondblclick="" attribute. This is treated
262 // as a separate event in other DOM-compliant browsers like Firefox, and so we do the same.
263 RefPtr<MouseEvent> doubleClickEvent = MouseEvent::create();
264 doubleClickEvent->initMouseEvent(eventNames().dblclickEvent,
265 mouseEvent->bubbles(), mouseEvent->cancelable(), mouseEvent->view(), mouseEvent->detail(),
266 mouseEvent->screenX(), mouseEvent->screenY(), mouseEvent->clientX(), mouseEvent->clientY(),
267 mouseEvent->ctrlKey(), mouseEvent->altKey(), mouseEvent->shiftKey(), mouseEvent->metaKey(),
268 mouseEvent->button(), relatedTarget);
270 if (mouseEvent->defaultHandled())
271 doubleClickEvent->setDefaultHandled();
273 dispatchEvent(doubleClickEvent);
274 if (doubleClickEvent->defaultHandled() || doubleClickEvent->defaultPrevented())
277 return didNotSwallowEvent;
281 bool Element::dispatchWheelEvent(const PlatformWheelEvent& event)
283 if (!event.deltaX() && !event.deltaY())
286 RefPtr<WheelEvent> wheelEvent = WheelEvent::create(event, document().defaultView());
287 return EventDispatcher::dispatchEvent(this, wheelEvent) && !wheelEvent->defaultHandled();
290 bool Element::dispatchKeyEvent(const PlatformKeyboardEvent& platformEvent)
292 RefPtr<KeyboardEvent> event = KeyboardEvent::create(platformEvent, document().defaultView());
293 if (Frame* frame = document().frame()) {
294 if (frame->eventHandler().accessibilityPreventsEventPropogation(event.get()))
295 event->stopPropagation();
297 return EventDispatcher::dispatchEvent(this, event) && !event->defaultHandled();
300 void Element::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
302 EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions, visualOptions);
305 RefPtr<Node> Element::cloneNodeInternal(Document& targetDocument, CloningOperation type)
308 case CloningOperation::OnlySelf:
309 case CloningOperation::SelfWithTemplateContent:
310 return cloneElementWithoutChildren(targetDocument);
311 case CloningOperation::Everything:
312 return cloneElementWithChildren(targetDocument);
314 ASSERT_NOT_REACHED();
318 RefPtr<Element> Element::cloneElementWithChildren(Document& targetDocument)
320 RefPtr<Element> clone = cloneElementWithoutChildren(targetDocument);
321 cloneChildNodes(clone.get());
322 return clone.release();
325 RefPtr<Element> Element::cloneElementWithoutChildren(Document& targetDocument)
327 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren(targetDocument);
328 // This will catch HTML elements in the wrong namespace that are not correctly copied.
329 // This is a sanity check as HTML overloads some of the DOM methods.
330 ASSERT(isHTMLElement() == clone->isHTMLElement());
332 clone->cloneDataFromElement(*this);
333 return clone.release();
336 RefPtr<Element> Element::cloneElementWithoutAttributesAndChildren(Document& targetDocument)
338 return targetDocument.createElement(tagQName(), false);
341 RefPtr<Attr> Element::detachAttribute(unsigned index)
343 ASSERT(elementData());
345 const Attribute& attribute = elementData()->attributeAt(index);
347 RefPtr<Attr> attrNode = attrIfExists(attribute.name());
349 detachAttrNodeFromElementWithValue(attrNode.get(), attribute.value());
351 attrNode = Attr::create(document(), attribute.name(), attribute.value());
353 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
354 return attrNode.release();
357 bool Element::removeAttribute(const QualifiedName& name)
362 unsigned index = elementData()->findAttributeIndexByName(name);
363 if (index == ElementData::attributeNotFound)
366 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
370 void Element::setBooleanAttribute(const QualifiedName& name, bool value)
373 setAttribute(name, emptyAtom);
375 removeAttribute(name);
378 NamedNodeMap& Element::attributes() const
380 ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
381 if (NamedNodeMap* attributeMap = rareData.attributeMap())
382 return *attributeMap;
384 rareData.setAttributeMap(std::make_unique<NamedNodeMap>(const_cast<Element&>(*this)));
385 return *rareData.attributeMap();
388 Node::NodeType Element::nodeType() const
393 bool Element::hasAttribute(const QualifiedName& name) const
395 return hasAttributeNS(name.namespaceURI(), name.localName());
398 void Element::synchronizeAllAttributes() const
402 if (elementData()->styleAttributeIsDirty()) {
403 ASSERT(isStyledElement());
404 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
407 if (elementData()->animatedSVGAttributesAreDirty()) {
408 ASSERT(isSVGElement());
409 downcast<SVGElement>(*this).synchronizeAnimatedSVGAttribute(anyQName());
413 ALWAYS_INLINE void Element::synchronizeAttribute(const QualifiedName& name) const
417 if (UNLIKELY(name == styleAttr && elementData()->styleAttributeIsDirty())) {
418 ASSERT_WITH_SECURITY_IMPLICATION(isStyledElement());
419 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
423 if (UNLIKELY(elementData()->animatedSVGAttributesAreDirty())) {
424 ASSERT(isSVGElement());
425 downcast<SVGElement>(*this).synchronizeAnimatedSVGAttribute(name);
429 ALWAYS_INLINE void Element::synchronizeAttribute(const AtomicString& localName) const
431 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
432 // e.g when called from DOM API.
435 // FIXME: this should be comparing in the ASCII range.
436 if (elementData()->styleAttributeIsDirty() && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(*this))) {
437 ASSERT_WITH_SECURITY_IMPLICATION(isStyledElement());
438 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
442 if (elementData()->animatedSVGAttributesAreDirty()) {
443 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
444 ASSERT_WITH_SECURITY_IMPLICATION(isSVGElement());
445 downcast<SVGElement>(*this).synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
449 const AtomicString& Element::getAttribute(const QualifiedName& name) const
453 synchronizeAttribute(name);
454 if (const Attribute* attribute = findAttributeByName(name))
455 return attribute->value();
459 bool Element::isFocusable() const
461 if (!inDocument() || !supportsFocus())
465 // If the node is in a display:none tree it might say it needs style recalc but
466 // the whole document is actually up to date.
467 ASSERT(!needsStyleRecalc() || !document().childNeedsStyleRecalc());
469 // Elements in canvas fallback content are not rendered, but they are allowed to be
470 // focusable as long as their canvas is displayed and visible.
471 if (auto* canvas = ancestorsOfType<HTMLCanvasElement>(*this).first())
472 return canvas->renderer() && canvas->renderer()->style().visibility() == VISIBLE;
475 // FIXME: Even if we are not visible, we might have a child that is visible.
476 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
477 if (!renderer() || renderer()->style().visibility() != VISIBLE)
483 bool Element::isUserActionElementInActiveChain() const
485 ASSERT(isUserActionElement());
486 return document().userActionElements().isInActiveChain(this);
489 bool Element::isUserActionElementActive() const
491 ASSERT(isUserActionElement());
492 return document().userActionElements().isActive(this);
495 bool Element::isUserActionElementFocused() const
497 ASSERT(isUserActionElement());
498 return document().userActionElements().isFocused(this);
501 bool Element::isUserActionElementHovered() const
503 ASSERT(isUserActionElement());
504 return document().userActionElements().isHovered(this);
507 void Element::setActive(bool flag, bool pause)
509 if (flag == active())
512 document().userActionElements().setActive(this, flag);
517 bool reactsToPress = renderStyle()->affectedByActive() || childrenAffectedByActive();
519 setNeedsStyleRecalc();
521 if (renderer()->style().hasAppearance() && renderer()->theme().stateChanged(*renderer(), ControlStates::PressedState))
522 reactsToPress = true;
524 // The rest of this function implements a feature that only works if the
525 // platform supports immediate invalidations on the ChromeClient, so bail if
526 // that isn't supported.
527 if (!document().page()->chrome().client().supportsImmediateInvalidation())
530 if (reactsToPress && pause) {
531 // The delay here is subtle. It relies on an assumption, namely that the amount of time it takes
532 // to repaint the "down" state of the control is about the same time as it would take to repaint the
533 // "up" state. Once you assume this, you can just delay for 100ms - that time (assuming that after you
534 // leave this method, it will be about that long before the flush of the up state happens again).
535 #ifdef HAVE_FUNC_USLEEP
536 double startTime = monotonicallyIncreasingTime();
539 document().updateStyleIfNeeded();
541 // Do an immediate repaint.
543 renderer()->repaint();
545 // FIXME: Come up with a less ridiculous way of doing this.
546 #ifdef HAVE_FUNC_USLEEP
547 // Now pause for a small amount of time (1/10th of a second from before we repainted in the pressed state)
548 double remainingTime = 0.1 - (monotonicallyIncreasingTime() - startTime);
549 if (remainingTime > 0)
550 usleep(static_cast<useconds_t>(remainingTime * 1000000.0));
555 void Element::setFocus(bool flag)
557 if (flag == focused())
560 document().userActionElements().setFocused(this, flag);
561 setNeedsStyleRecalc();
564 void Element::setHovered(bool flag)
566 if (flag == hovered())
569 document().userActionElements().setHovered(this, flag);
572 // When setting hover to false, the style needs to be recalc'd even when
573 // there's no renderer (imagine setting display:none in the :hover class,
574 // if a nil renderer would prevent this element from recalculating its
575 // style, it would never go back to its normal style and remain
576 // stuck in its hovered style).
578 setNeedsStyleRecalc();
583 if (renderer()->style().affectedByHover() || childrenAffectedByHover())
584 setNeedsStyleRecalc();
586 if (renderer()->style().hasAppearance())
587 renderer()->theme().stateChanged(*renderer(), ControlStates::HoverState);
590 void Element::scrollIntoView(bool alignToTop)
592 document().updateLayoutIgnorePendingStylesheets();
597 LayoutRect bounds = renderer()->anchorRect();
598 // Align to the top / bottom and to the closest edge.
600 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
602 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
605 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
607 document().updateLayoutIgnorePendingStylesheets();
612 LayoutRect bounds = renderer()->anchorRect();
614 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
616 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
619 void Element::scrollIntoViewIfNotVisible(bool centerIfNotVisible)
621 document().updateLayoutIgnorePendingStylesheets();
626 LayoutRect bounds = renderer()->anchorRect();
627 if (centerIfNotVisible)
628 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNotVisible, ScrollAlignment::alignCenterIfNotVisible);
630 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNotVisible, ScrollAlignment::alignToEdgeIfNotVisible);
633 void Element::scrollByUnits(int units, ScrollGranularity granularity)
635 document().updateLayoutIgnorePendingStylesheets();
640 if (!renderer()->hasOverflowClip())
643 ScrollDirection direction = ScrollDown;
645 direction = ScrollUp;
648 Element* stopElement = this;
649 downcast<RenderBox>(*renderer()).scroll(direction, granularity, units, &stopElement);
652 void Element::scrollByLines(int lines)
654 scrollByUnits(lines, ScrollByLine);
657 void Element::scrollByPages(int pages)
659 scrollByUnits(pages, ScrollByPage);
662 static double localZoomForRenderer(const RenderElement& renderer)
664 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
665 // other out, but the alternative is that we'd have to crawl up the whole render tree every
666 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
667 double zoomFactor = 1;
668 if (renderer.style().effectiveZoom() != 1) {
669 // Need to find the nearest enclosing RenderElement that set up
670 // a differing zoom, and then we divide our result by it to eliminate the zoom.
671 const RenderElement* prev = &renderer;
672 for (RenderElement* curr = prev->parent(); curr; curr = curr->parent()) {
673 if (curr->style().effectiveZoom() != prev->style().effectiveZoom()) {
674 zoomFactor = prev->style().zoom();
679 if (prev->isRenderView())
680 zoomFactor = prev->style().zoom();
685 static double adjustForLocalZoom(LayoutUnit value, const RenderElement& renderer, double& zoomFactor)
687 zoomFactor = localZoomForRenderer(renderer);
689 return value.toDouble();
690 return value.toDouble() / zoomFactor;
693 enum LegacyCSSOMElementMetricsRoundingStrategy { Round, Floor };
695 static bool subpixelMetricsEnabled(const Document& document)
697 return document.settings() && document.settings()->subpixelCSSOMElementMetricsEnabled();
700 static double convertToNonSubpixelValueIfNeeded(double value, const Document& document, LegacyCSSOMElementMetricsRoundingStrategy roundStrategy = Round)
702 return subpixelMetricsEnabled(document) ? value : roundStrategy == Round ? round(value) : floor(value);
705 double Element::offsetLeft()
707 document().updateLayoutIgnorePendingStylesheets();
708 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
709 LayoutUnit offsetLeft = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetLeft() : LayoutUnit(renderer->pixelSnappedOffsetLeft());
710 double zoomFactor = 1;
711 double offsetLeftAdjustedWithZoom = adjustForLocalZoom(offsetLeft, *renderer, zoomFactor);
712 return convertToNonSubpixelValueIfNeeded(offsetLeftAdjustedWithZoom, renderer->document(), zoomFactor == 1 ? Floor : Round);
717 double Element::offsetTop()
719 document().updateLayoutIgnorePendingStylesheets();
720 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
721 LayoutUnit offsetTop = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetTop() : LayoutUnit(renderer->pixelSnappedOffsetTop());
722 double zoomFactor = 1;
723 double offsetTopAdjustedWithZoom = adjustForLocalZoom(offsetTop, *renderer, zoomFactor);
724 return convertToNonSubpixelValueIfNeeded(offsetTopAdjustedWithZoom, renderer->document(), zoomFactor == 1 ? Floor : Round);
729 double Element::offsetWidth()
731 document().updateLayoutIfDimensionsOutOfDate(this, WidthDimensionsCheck);
732 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
733 LayoutUnit offsetWidth = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetWidth() : LayoutUnit(renderer->pixelSnappedOffsetWidth());
734 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(offsetWidth, *renderer).toDouble(), renderer->document());
739 double Element::offsetHeight()
741 document().updateLayoutIfDimensionsOutOfDate(this, HeightDimensionsCheck);
742 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
743 LayoutUnit offsetHeight = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetHeight() : LayoutUnit(renderer->pixelSnappedOffsetHeight());
744 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(offsetHeight, *renderer).toDouble(), renderer->document());
749 Element* Element::bindingsOffsetParent()
751 Element* element = offsetParent();
752 if (!element || !element->isInShadowTree())
754 return element->containingShadowRoot()->type() == ShadowRoot::UserAgentShadowRoot ? 0 : element;
757 Element* Element::offsetParent()
759 document().updateLayoutIgnorePendingStylesheets();
760 auto renderer = this->renderer();
763 auto offsetParent = renderer->offsetParent();
766 return offsetParent->element();
769 double Element::clientLeft()
771 document().updateLayoutIgnorePendingStylesheets();
773 if (RenderBox* renderer = renderBox()) {
774 LayoutUnit clientLeft = subpixelMetricsEnabled(renderer->document()) ? renderer->clientLeft() : LayoutUnit(roundToInt(renderer->clientLeft()));
775 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientLeft, *renderer).toDouble(), renderer->document());
780 double Element::clientTop()
782 document().updateLayoutIgnorePendingStylesheets();
784 if (RenderBox* renderer = renderBox()) {
785 LayoutUnit clientTop = subpixelMetricsEnabled(renderer->document()) ? renderer->clientTop() : LayoutUnit(roundToInt(renderer->clientTop()));
786 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientTop, *renderer).toDouble(), renderer->document());
791 double Element::clientWidth()
793 document().updateLayoutIgnorePendingStylesheets();
795 if (!document().hasLivingRenderTree())
797 RenderView& renderView = *document().renderView();
799 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
800 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
801 bool inQuirksMode = document().inQuirksMode();
802 if ((!inQuirksMode && document().documentElement() == this) || (inQuirksMode && isHTMLElement() && document().bodyOrFrameset() == this))
803 return adjustForAbsoluteZoom(renderView.frameView().layoutWidth(), renderView);
805 if (RenderBox* renderer = renderBox()) {
806 LayoutUnit clientWidth = subpixelMetricsEnabled(renderer->document()) ? renderer->clientWidth() : LayoutUnit(renderer->pixelSnappedClientWidth());
807 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientWidth, *renderer).toDouble(), renderer->document());
812 double Element::clientHeight()
814 document().updateLayoutIgnorePendingStylesheets();
816 if (!document().hasLivingRenderTree())
818 RenderView& renderView = *document().renderView();
820 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
821 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
822 bool inQuirksMode = document().inQuirksMode();
823 if ((!inQuirksMode && document().documentElement() == this) || (inQuirksMode && isHTMLElement() && document().bodyOrFrameset() == this))
824 return adjustForAbsoluteZoom(renderView.frameView().layoutHeight(), renderView);
826 if (RenderBox* renderer = renderBox()) {
827 LayoutUnit clientHeight = subpixelMetricsEnabled(renderer->document()) ? renderer->clientHeight() : LayoutUnit(renderer->pixelSnappedClientHeight());
828 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientHeight, *renderer).toDouble(), renderer->document());
833 int Element::scrollLeft()
835 document().updateLayoutIgnorePendingStylesheets();
837 if (RenderBox* rend = renderBox())
838 return adjustForAbsoluteZoom(rend->scrollLeft(), *rend);
842 int Element::scrollTop()
844 document().updateLayoutIgnorePendingStylesheets();
846 if (RenderBox* rend = renderBox())
847 return adjustForAbsoluteZoom(rend->scrollTop(), *rend);
851 void Element::setScrollLeft(int newLeft)
853 document().updateLayoutIgnorePendingStylesheets();
855 if (RenderBox* renderer = renderBox()) {
856 renderer->setScrollLeft(static_cast<int>(newLeft * renderer->style().effectiveZoom()));
857 if (auto* scrollableArea = renderer->layer())
858 scrollableArea->setScrolledProgrammatically(true);
862 void Element::setScrollTop(int newTop)
864 document().updateLayoutIgnorePendingStylesheets();
866 if (RenderBox* renderer = renderBox()) {
867 renderer->setScrollTop(static_cast<int>(newTop * renderer->style().effectiveZoom()));
868 if (auto* scrollableArea = renderer->layer())
869 scrollableArea->setScrolledProgrammatically(true);
873 int Element::scrollWidth()
875 document().updateLayoutIgnorePendingStylesheets();
876 if (RenderBox* rend = renderBox())
877 return adjustForAbsoluteZoom(rend->scrollWidth(), *rend);
881 int Element::scrollHeight()
883 document().updateLayoutIgnorePendingStylesheets();
884 if (RenderBox* rend = renderBox())
885 return adjustForAbsoluteZoom(rend->scrollHeight(), *rend);
889 IntRect Element::boundsInRootViewSpace()
891 document().updateLayoutIgnorePendingStylesheets();
893 FrameView* view = document().view();
897 Vector<FloatQuad> quads;
899 if (isSVGElement() && renderer()) {
900 // Get the bounding rectangle from the SVG model.
901 SVGElement& svgElement = downcast<SVGElement>(*this);
903 if (svgElement.getBoundingBox(localRect))
904 quads.append(renderer()->localToAbsoluteQuad(localRect));
906 // Get the bounding rectangle from the box model.
907 if (renderBoxModelObject())
908 renderBoxModelObject()->absoluteQuads(quads);
914 IntRect result = quads[0].enclosingBoundingBox();
915 for (size_t i = 1; i < quads.size(); ++i)
916 result.unite(quads[i].enclosingBoundingBox());
918 result = view->contentsToRootView(result);
922 Ref<ClientRectList> Element::getClientRects()
924 document().updateLayoutIgnorePendingStylesheets();
926 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
927 if (!renderBoxModelObject)
928 return ClientRectList::create();
930 // FIXME: Handle SVG elements.
931 // FIXME: Handle table/inline-table with a caption.
933 Vector<FloatQuad> quads;
934 renderBoxModelObject->absoluteQuads(quads);
935 document().adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(quads, renderBoxModelObject->style());
936 return ClientRectList::create(quads);
939 Ref<ClientRect> Element::getBoundingClientRect()
941 document().updateLayoutIgnorePendingStylesheets();
943 Vector<FloatQuad> quads;
944 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
945 // Get the bounding rectangle from the SVG model.
946 SVGElement& svgElement = downcast<SVGElement>(*this);
948 if (svgElement.getBoundingBox(localRect))
949 quads.append(renderer()->localToAbsoluteQuad(localRect));
951 // Get the bounding rectangle from the box model.
952 if (renderBoxModelObject())
953 renderBoxModelObject()->absoluteQuads(quads);
957 return ClientRect::create();
959 FloatRect result = quads[0].boundingBox();
960 for (size_t i = 1; i < quads.size(); ++i)
961 result.unite(quads[i].boundingBox());
963 document().adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(result, renderer()->style());
964 return ClientRect::create(result);
967 IntRect Element::clientRect() const
969 if (RenderObject* renderer = this->renderer())
970 return document().view()->contentsToRootView(renderer->absoluteBoundingBoxRect());
974 IntRect Element::screenRect() const
976 if (RenderObject* renderer = this->renderer())
977 return document().view()->contentsToScreen(renderer->absoluteBoundingBoxRect());
981 const AtomicString& Element::getAttribute(const AtomicString& localName) const
985 synchronizeAttribute(localName);
986 if (const Attribute* attribute = elementData()->findAttributeByName(localName, shouldIgnoreAttributeCase(*this)))
987 return attribute->value();
991 const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
993 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
996 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionCode& ec)
998 if (!Document::isValidName(localName)) {
999 ec = INVALID_CHARACTER_ERR;
1003 synchronizeAttribute(localName);
1004 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(*this) ? localName.convertToASCIILowercase() : localName;
1006 unsigned index = elementData() ? elementData()->findAttributeIndexByName(caseAdjustedLocalName, false) : ElementData::attributeNotFound;
1007 const QualifiedName& qName = index != ElementData::attributeNotFound ? attributeAt(index).name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
1008 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
1011 void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
1013 synchronizeAttribute(name);
1014 unsigned index = elementData() ? elementData()->findAttributeIndexByName(name) : ElementData::attributeNotFound;
1015 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
1018 void Element::setAttributeWithoutSynchronization(const QualifiedName& name, const AtomicString& value)
1020 unsigned index = elementData() ? elementData()->findAttributeIndexByName(name) : ElementData::attributeNotFound;
1021 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
1024 void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
1026 unsigned index = elementData() ? elementData()->findAttributeIndexByName(name) : ElementData::attributeNotFound;
1027 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
1030 inline void Element::setAttributeInternal(unsigned index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1032 if (newValue.isNull()) {
1033 if (index != ElementData::attributeNotFound)
1034 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
1038 if (index == ElementData::attributeNotFound) {
1039 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
1043 const Attribute& attribute = attributeAt(index);
1044 AtomicString oldValue = attribute.value();
1045 bool valueChanged = newValue != oldValue;
1046 QualifiedName attributeName = (!inSynchronizationOfLazyAttribute || valueChanged) ? attribute.name() : name;
1048 if (!inSynchronizationOfLazyAttribute)
1049 willModifyAttribute(attributeName, oldValue, newValue);
1052 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
1053 // will write into the ElementData.
1054 // FIXME: Refactor this so it makes some sense.
1055 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(attributeName))
1056 attrNode->setValue(newValue);
1058 ensureUniqueElementData().attributeAt(index).setValue(newValue);
1061 if (!inSynchronizationOfLazyAttribute)
1062 didModifyAttribute(attributeName, oldValue, newValue);
1065 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
1068 return value.lower();
1072 static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, StyleResolver* styleResolver)
1074 ASSERT(newId != oldId);
1075 if (!oldId.isEmpty() && styleResolver->hasSelectorForId(oldId))
1077 if (!newId.isEmpty() && styleResolver->hasSelectorForId(newId))
1082 void Element::attributeChanged(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue, AttributeModificationReason)
1084 parseAttribute(name, newValue);
1086 document().incDOMTreeVersion();
1088 if (oldValue == newValue)
1091 StyleResolver* styleResolver = document().styleResolverIfExists();
1092 bool testShouldInvalidateStyle = inRenderedDocument() && styleResolver && styleChangeType() < FullStyleChange;
1093 bool shouldInvalidateStyle = false;
1095 if (name == HTMLNames::idAttr) {
1096 AtomicString oldId = elementData()->idForStyleResolution();
1097 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1098 if (newId != oldId) {
1099 elementData()->setIdForStyleResolution(newId);
1100 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver);
1102 } else if (name == classAttr)
1103 classAttributeChanged(newValue);
1104 else if (name == HTMLNames::nameAttr)
1105 elementData()->setHasNameAttribute(!newValue.isNull());
1106 else if (name == HTMLNames::pseudoAttr)
1107 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
1110 invalidateNodeListAndCollectionCachesInAncestors(&name, this);
1112 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
1113 shouldInvalidateStyle |= !styleResolver;
1115 if (shouldInvalidateStyle)
1116 setNeedsStyleRecalc();
1118 if (AXObjectCache* cache = document().existingAXObjectCache())
1119 cache->handleAttributeChanged(name, this);
1122 template <typename CharacterType>
1123 static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
1129 if (isNotHTMLSpace(characters[i]))
1132 } while (i < length);
1137 static inline bool classStringHasClassName(const AtomicString& newClassString)
1139 unsigned length = newClassString.length();
1144 if (newClassString.is8Bit())
1145 return classStringHasClassName(newClassString.characters8(), length);
1146 return classStringHasClassName(newClassString.characters16(), length);
1149 static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const StyleResolver& styleResolver)
1151 unsigned changedSize = changedClasses.size();
1152 for (unsigned i = 0; i < changedSize; ++i) {
1153 if (styleResolver.hasSelectorForClass(changedClasses[i]))
1159 static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const StyleResolver& styleResolver)
1161 unsigned oldSize = oldClasses.size();
1163 return checkSelectorForClassChange(newClasses, styleResolver);
1164 BitVector remainingClassBits;
1165 remainingClassBits.ensureSize(oldSize);
1166 // Class vectors tend to be very short. This is faster than using a hash table.
1167 unsigned newSize = newClasses.size();
1168 for (unsigned i = 0; i < newSize; ++i) {
1169 bool foundFromBoth = false;
1170 for (unsigned j = 0; j < oldSize; ++j) {
1171 if (newClasses[i] == oldClasses[j]) {
1172 remainingClassBits.quickSet(j);
1173 foundFromBoth = true;
1178 if (styleResolver.hasSelectorForClass(newClasses[i]))
1181 for (unsigned i = 0; i < oldSize; ++i) {
1182 // If the bit is not set the the corresponding class has been removed.
1183 if (remainingClassBits.quickGet(i))
1185 if (styleResolver.hasSelectorForClass(oldClasses[i]))
1191 void Element::classAttributeChanged(const AtomicString& newClassString)
1193 StyleResolver* styleResolver = document().styleResolverIfExists();
1194 bool testShouldInvalidateStyle = inRenderedDocument() && styleResolver && styleChangeType() < FullStyleChange;
1195 bool shouldInvalidateStyle = false;
1197 if (classStringHasClassName(newClassString)) {
1198 const bool shouldFoldCase = document().inQuirksMode();
1199 // Note: We'll need ElementData, but it doesn't have to be UniqueElementData.
1201 ensureUniqueElementData();
1202 const SpaceSplitString oldClasses = elementData()->classNames();
1203 elementData()->setClass(newClassString, shouldFoldCase);
1204 const SpaceSplitString& newClasses = elementData()->classNames();
1205 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver);
1206 } else if (elementData()) {
1207 const SpaceSplitString& oldClasses = elementData()->classNames();
1208 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver);
1209 elementData()->clearClass();
1213 elementRareData()->clearClassListValueForQuirksMode();
1215 if (shouldInvalidateStyle)
1216 setNeedsStyleRecalc();
1219 URL Element::absoluteLinkURL() const
1224 AtomicString linkAttribute;
1225 if (hasTagName(SVGNames::aTag))
1226 linkAttribute = getAttribute(XLinkNames::hrefAttr);
1228 linkAttribute = getAttribute(HTMLNames::hrefAttr);
1230 if (linkAttribute.isEmpty())
1233 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(linkAttribute));
1236 WeakPtr<Element> Element::createWeakPtr()
1238 return ensureElementRareData().weakPtrFactory().createWeakPtr();
1241 // Returns true is the given attribute is an event handler.
1242 // We consider an event handler any attribute that begins with "on".
1243 // It is a simple solution that has the advantage of not requiring any
1244 // code or configuration change if a new event handler is defined.
1246 static inline bool isEventHandlerAttribute(const Attribute& attribute)
1248 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1251 bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1253 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1256 void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1258 size_t destination = 0;
1259 for (size_t source = 0; source < attributeVector.size(); ++source) {
1260 if (isEventHandlerAttribute(attributeVector[source])
1261 || isJavaScriptURLAttribute(attributeVector[source])
1262 || isHTMLContentAttribute(attributeVector[source]))
1265 if (source != destination)
1266 attributeVector[destination] = attributeVector[source];
1270 attributeVector.shrink(destination);
1273 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1275 ASSERT(!inDocument());
1276 ASSERT(!parentNode());
1277 ASSERT(!m_elementData);
1279 if (!attributeVector.isEmpty()) {
1280 if (document().sharedObjectPool())
1281 m_elementData = document().sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
1283 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1287 parserDidSetAttributes();
1289 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1290 for (const auto& attribute : attributeVector)
1291 attributeChanged(attribute.name(), nullAtom, attribute.value(), ModifiedDirectly);
1294 void Element::parserDidSetAttributes()
1298 bool Element::hasAttributes() const
1300 synchronizeAllAttributes();
1301 return elementData() && elementData()->length();
1304 bool Element::hasEquivalentAttributes(const Element* other) const
1306 synchronizeAllAttributes();
1307 other->synchronizeAllAttributes();
1308 if (elementData() == other->elementData())
1311 return elementData()->isEquivalent(other->elementData());
1312 if (other->elementData())
1313 return other->elementData()->isEquivalent(elementData());
1317 String Element::nodeName() const
1319 return m_tagName.toString();
1322 String Element::nodeNamePreservingCase() const
1324 return m_tagName.toString();
1327 void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec)
1330 checkSetPrefix(prefix, ec);
1334 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1337 URL Element::baseURI() const
1339 const AtomicString& baseAttribute = getAttribute(baseAttr);
1340 URL base(URL(), baseAttribute);
1341 if (!base.protocol().isEmpty())
1344 ContainerNode* parent = parentNode();
1348 const URL& parentBase = parent->baseURI();
1349 if (parentBase.isNull())
1352 return URL(parentBase, baseAttribute);
1355 const AtomicString& Element::imageSourceURL() const
1357 return fastGetAttribute(srcAttr);
1360 bool Element::rendererIsNeeded(const RenderStyle& style)
1362 return style.display() != NONE;
1365 RenderPtr<RenderElement> Element::createElementRenderer(Ref<RenderStyle>&& style)
1367 return RenderElement::createFor(*this, WTF::move(style));
1370 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode& insertionPoint)
1372 bool wasInDocument = inDocument();
1373 // need to do superclass processing first so inDocument() is true
1374 // by the time we reach updateId
1375 ContainerNode::insertedInto(insertionPoint);
1376 ASSERT(!wasInDocument || inDocument());
1378 #if ENABLE(FULLSCREEN_API)
1379 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1380 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1383 if (!insertionPoint.isInTreeScope())
1384 return InsertionDone;
1387 elementRareData()->clearClassListValueForQuirksMode();
1389 TreeScope* newScope = &insertionPoint.treeScope();
1390 HTMLDocument* newDocument = !wasInDocument && inDocument() && is<HTMLDocument>(newScope->documentScope()) ? &downcast<HTMLDocument>(newScope->documentScope()) : nullptr;
1391 if (newScope != &treeScope())
1394 const AtomicString& idValue = getIdAttribute();
1395 if (!idValue.isNull()) {
1397 updateIdForTreeScope(*newScope, nullAtom, idValue);
1399 updateIdForDocument(*newDocument, nullAtom, idValue, AlwaysUpdateHTMLDocumentNamedItemMaps);
1402 const AtomicString& nameValue = getNameAttribute();
1403 if (!nameValue.isNull()) {
1405 updateNameForTreeScope(*newScope, nullAtom, nameValue);
1407 updateNameForDocument(*newDocument, nullAtom, nameValue);
1410 if (newScope && hasTagName(labelTag)) {
1411 if (newScope->shouldCacheLabelsByForAttribute())
1412 updateLabel(*newScope, nullAtom, fastGetAttribute(forAttr));
1415 return InsertionDone;
1418 void Element::removedFrom(ContainerNode& insertionPoint)
1420 #if ENABLE(FULLSCREEN_API)
1421 if (containsFullScreenElement())
1422 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1424 #if ENABLE(POINTER_LOCK)
1425 if (document().page())
1426 document().page()->pointerLockController().elementRemoved(this);
1429 setSavedLayerScrollOffset(IntSize());
1431 if (insertionPoint.isInTreeScope()) {
1432 TreeScope* oldScope = &insertionPoint.treeScope();
1433 HTMLDocument* oldDocument = inDocument() && is<HTMLDocument>(oldScope->documentScope()) ? &downcast<HTMLDocument>(oldScope->documentScope()) : nullptr;
1434 if (oldScope != &treeScope() || !isInTreeScope())
1437 const AtomicString& idValue = getIdAttribute();
1438 if (!idValue.isNull()) {
1440 updateIdForTreeScope(*oldScope, idValue, nullAtom);
1442 updateIdForDocument(*oldDocument, idValue, nullAtom, AlwaysUpdateHTMLDocumentNamedItemMaps);
1445 const AtomicString& nameValue = getNameAttribute();
1446 if (!nameValue.isNull()) {
1448 updateNameForTreeScope(*oldScope, nameValue, nullAtom);
1450 updateNameForDocument(*oldDocument, nameValue, nullAtom);
1453 if (oldScope && hasTagName(labelTag)) {
1454 if (oldScope->shouldCacheLabelsByForAttribute())
1455 updateLabel(*oldScope, fastGetAttribute(forAttr), nullAtom);
1459 ContainerNode::removedFrom(insertionPoint);
1461 if (hasPendingResources())
1462 document().accessSVGExtensions().removeElementFromPendingResources(this);
1465 void Element::unregisterNamedFlowContentElement()
1467 if (document().cssRegionsEnabled() && isNamedFlowContentNode() && document().renderView())
1468 document().renderView()->flowThreadController().unregisterNamedFlowContentElement(*this);
1471 ShadowRoot* Element::shadowRoot() const
1473 return hasRareData() ? elementRareData()->shadowRoot() : 0;
1476 static bool shouldUseNodeRenderingTraversalSlowPath(const Element& element)
1478 if (element.isShadowRoot())
1480 return element.isInsertionPoint() || element.shadowRoot();
1483 void Element::resetNeedsNodeRenderingTraversalSlowPath()
1485 setNeedsNodeRenderingTraversalSlowPath(shouldUseNodeRenderingTraversalSlowPath(*this));
1488 void Element::addShadowRoot(Ref<ShadowRoot>&& newShadowRoot)
1490 ASSERT(!shadowRoot());
1492 ShadowRoot& shadowRoot = newShadowRoot.get();
1493 ensureElementRareData().setShadowRoot(WTF::move(newShadowRoot));
1495 shadowRoot.setHostElement(this);
1496 shadowRoot.setParentTreeScope(&treeScope());
1497 shadowRoot.distributor().didShadowBoundaryChange(this);
1499 ChildNodeInsertionNotifier(*this).notify(shadowRoot);
1501 resetNeedsNodeRenderingTraversalSlowPath();
1503 setNeedsStyleRecalc(ReconstructRenderTree);
1505 InspectorInstrumentation::didPushShadowRoot(*this, shadowRoot);
1508 void Element::removeShadowRoot()
1510 RefPtr<ShadowRoot> oldRoot = shadowRoot();
1513 InspectorInstrumentation::willPopShadowRoot(*this, *oldRoot);
1514 document().removeFocusedNodeOfSubtree(oldRoot.get());
1516 ASSERT(!oldRoot->renderer());
1518 elementRareData()->clearShadowRoot();
1520 oldRoot->setHostElement(0);
1521 oldRoot->setParentTreeScope(&document());
1523 ChildNodeRemovalNotifier(*this).notify(*oldRoot);
1525 oldRoot->distributor().invalidateDistribution(this);
1528 RefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1530 if (alwaysCreateUserAgentShadowRoot())
1531 ensureUserAgentShadowRoot();
1533 ec = HIERARCHY_REQUEST_ERR;
1537 ShadowRoot* Element::userAgentShadowRoot() const
1539 if (ShadowRoot* shadowRoot = this->shadowRoot()) {
1540 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1546 ShadowRoot& Element::ensureUserAgentShadowRoot()
1548 ShadowRoot* shadowRoot = userAgentShadowRoot();
1550 addShadowRoot(ShadowRoot::create(document(), ShadowRoot::UserAgentShadowRoot));
1551 shadowRoot = userAgentShadowRoot();
1552 didAddUserAgentShadowRoot(shadowRoot);
1557 const AtomicString& Element::shadowPseudoId() const
1562 bool Element::childTypeAllowed(NodeType type) const
1568 case PROCESSING_INSTRUCTION_NODE:
1569 case CDATA_SECTION_NODE:
1570 case ENTITY_REFERENCE_NODE:
1578 static void checkForEmptyStyleChange(Element& element)
1580 if (element.styleAffectedByEmpty()) {
1581 RenderStyle* style = element.renderStyle();
1582 if (!style || (!style->emptyState() || element.hasChildNodes()))
1583 element.setNeedsStyleRecalc();
1587 enum SiblingCheckType { FinishedParsingChildren, SiblingElementRemoved, Other };
1589 static void checkForSiblingStyleChanges(Element& parent, SiblingCheckType checkType, Element* elementBeforeChange, Element* elementAfterChange)
1592 checkForEmptyStyleChange(parent);
1594 if (parent.styleChangeType() >= FullStyleChange)
1597 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1598 // In the DOM case, we only need to do something if |afterChange| is not 0.
1599 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1600 if (parent.childrenAffectedByFirstChildRules() && elementAfterChange) {
1601 // Find our new first child.
1602 Element* newFirstElement = ElementTraversal::firstChild(parent);
1603 // Find the first element node following |afterChange|
1605 // This is the insert/append case.
1606 if (newFirstElement != elementAfterChange) {
1607 RenderStyle* style = elementAfterChange->renderStyle();
1608 if (!style || style->firstChildState())
1609 elementAfterChange->setNeedsStyleRecalc();
1612 // We also have to handle node removal.
1613 if (checkType == SiblingElementRemoved && newFirstElement == elementAfterChange && newFirstElement) {
1614 RenderStyle* style = newFirstElement->renderStyle();
1615 if (!style || !style->firstChildState())
1616 newFirstElement->setNeedsStyleRecalc();
1620 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1621 // In the DOM case, we only need to do something if |afterChange| is not 0.
1622 if (parent.childrenAffectedByLastChildRules() && elementBeforeChange) {
1623 // Find our new last child.
1624 Element* newLastElement = ElementTraversal::lastChild(parent);
1626 if (newLastElement != elementBeforeChange) {
1627 RenderStyle* style = elementBeforeChange->renderStyle();
1628 if (!style || style->lastChildState())
1629 elementBeforeChange->setNeedsStyleRecalc();
1632 // We also have to handle node removal. The parser callback case is similar to node removal as well in that we need to change the last child
1634 if ((checkType == SiblingElementRemoved || checkType == FinishedParsingChildren) && newLastElement == elementBeforeChange && newLastElement) {
1635 RenderStyle* style = newLastElement->renderStyle();
1636 if (!style || !style->lastChildState())
1637 newLastElement->setNeedsStyleRecalc();
1641 if (elementAfterChange) {
1642 if (elementAfterChange->styleIsAffectedByPreviousSibling())
1643 elementAfterChange->setNeedsStyleRecalc();
1644 else if (elementAfterChange->affectsNextSiblingElementStyle()) {
1645 Element* elementToInvalidate = elementAfterChange;
1647 elementToInvalidate = elementToInvalidate->nextElementSibling();
1648 } while (elementToInvalidate && !elementToInvalidate->styleIsAffectedByPreviousSibling());
1650 if (elementToInvalidate)
1651 elementToInvalidate->setNeedsStyleRecalc();
1655 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1656 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1658 // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
1659 // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
1660 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1661 if (parent.childrenAffectedByBackwardPositionalRules() && elementBeforeChange)
1662 parent.setNeedsStyleRecalc();
1665 void Element::childrenChanged(const ChildChange& change)
1667 ContainerNode::childrenChanged(change);
1668 if (change.source == ChildChangeSourceParser)
1669 checkForEmptyStyleChange(*this);
1671 SiblingCheckType checkType = change.type == ElementRemoved ? SiblingElementRemoved : Other;
1672 checkForSiblingStyleChanges(*this, checkType, change.previousSiblingElement, change.nextSiblingElement);
1675 if (ShadowRoot* shadowRoot = this->shadowRoot())
1676 shadowRoot->invalidateDistribution();
1679 void Element::removeAllEventListeners()
1681 ContainerNode::removeAllEventListeners();
1682 if (ShadowRoot* shadowRoot = this->shadowRoot())
1683 shadowRoot->removeAllEventListeners();
1686 void Element::beginParsingChildren()
1688 clearIsParsingChildrenFinished();
1689 if (auto styleResolver = document().styleResolverIfExists())
1690 styleResolver->pushParentElement(this);
1693 void Element::finishParsingChildren()
1695 ContainerNode::finishParsingChildren();
1696 setIsParsingChildrenFinished();
1697 checkForSiblingStyleChanges(*this, FinishedParsingChildren, ElementTraversal::lastChild(*this), nullptr);
1698 if (auto styleResolver = document().styleResolverIfExists())
1699 styleResolver->popParentElement(this);
1702 #if ENABLE(TREE_DEBUGGING)
1703 void Element::formatForDebugger(char* buffer, unsigned length) const
1705 StringBuilder result;
1708 result.append(nodeName());
1710 s = getIdAttribute();
1711 if (s.length() > 0) {
1712 if (result.length() > 0)
1713 result.appendLiteral("; ");
1714 result.appendLiteral("id=");
1718 s = getAttribute(classAttr);
1719 if (s.length() > 0) {
1720 if (result.length() > 0)
1721 result.appendLiteral("; ");
1722 result.appendLiteral("class=");
1726 strncpy(buffer, result.toString().utf8().data(), length - 1);
1730 const Vector<RefPtr<Attr>>& Element::attrNodeList()
1732 ASSERT(hasSyntheticAttrChildNodes());
1733 return *attrNodeListForElement(*this);
1736 RefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1739 ec = TYPE_MISMATCH_ERR;
1743 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName().localName(), shouldIgnoreAttributeCase(*this));
1744 if (oldAttrNode.get() == attrNode)
1745 return attrNode; // This Attr is already attached to the element.
1747 // INUSE_ATTRIBUTE_ERR: Raised if node is an Attr that is already an attribute of another Element object.
1748 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1749 if (attrNode->ownerElement() && attrNode->ownerElement() != this) {
1750 ec = INUSE_ATTRIBUTE_ERR;
1754 synchronizeAllAttributes();
1755 UniqueElementData& elementData = ensureUniqueElementData();
1757 unsigned existingAttributeIndex = elementData.findAttributeIndexByName(attrNode->qualifiedName().localName(), shouldIgnoreAttributeCase(*this));
1758 if (existingAttributeIndex != ElementData::attributeNotFound) {
1759 const Attribute& attribute = attributeAt(existingAttributeIndex);
1761 detachAttrNodeFromElementWithValue(oldAttrNode.get(), attribute.value());
1763 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), attribute.value());
1765 if (attribute.name().matches(attrNode->qualifiedName()))
1766 setAttributeInternal(existingAttributeIndex, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1768 removeAttributeInternal(existingAttributeIndex, NotInSynchronizationOfLazyAttribute);
1769 unsigned existingAttributeIndexForFullQualifiedName = elementData.findAttributeIndexByName(attrNode->qualifiedName());
1770 setAttributeInternal(existingAttributeIndexForFullQualifiedName, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1773 unsigned existingAttributeIndexForFullQualifiedName = elementData.findAttributeIndexByName(attrNode->qualifiedName());
1774 setAttributeInternal(existingAttributeIndexForFullQualifiedName, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1776 if (attrNode->ownerElement() != this) {
1777 attrNode->attachToElement(this);
1778 treeScope().adoptIfNeeded(attrNode);
1779 ensureAttrNodeListForElement(*this).append(attrNode);
1784 RefPtr<Attr> Element::setAttributeNodeNS(Attr* attrNode, ExceptionCode& ec)
1787 ec = TYPE_MISMATCH_ERR;
1791 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1792 if (oldAttrNode.get() == attrNode)
1793 return attrNode; // This Attr is already attached to the element.
1795 // INUSE_ATTRIBUTE_ERR: Raised if node is an Attr that is already an attribute of another Element object.
1796 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1797 if (attrNode->ownerElement() && attrNode->ownerElement() != this) {
1798 ec = INUSE_ATTRIBUTE_ERR;
1802 synchronizeAllAttributes();
1803 UniqueElementData& elementData = ensureUniqueElementData();
1805 unsigned index = elementData.findAttributeIndexByName(attrNode->qualifiedName());
1806 if (index != ElementData::attributeNotFound) {
1808 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData.attributeAt(index).value());
1810 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData.attributeAt(index).value());
1813 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1815 attrNode->attachToElement(this);
1816 treeScope().adoptIfNeeded(attrNode);
1817 ensureAttrNodeListForElement(*this).append(attrNode);
1819 return oldAttrNode.release();
1822 RefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1825 ec = TYPE_MISMATCH_ERR;
1828 if (attr->ownerElement() != this) {
1833 ASSERT(&document() == &attr->document());
1835 synchronizeAllAttributes();
1837 if (!m_elementData) {
1842 unsigned existingAttributeIndex = m_elementData->findAttributeIndexByName(attr->qualifiedName());
1844 if (existingAttributeIndex == ElementData::attributeNotFound) {
1849 RefPtr<Attr> attrNode = attr;
1850 detachAttrNodeFromElementWithValue(attr, m_elementData->attributeAt(existingAttributeIndex).value());
1851 removeAttributeInternal(existingAttributeIndex, NotInSynchronizationOfLazyAttribute);
1855 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1857 String prefix, localName;
1858 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1862 QualifiedName qName(prefix, localName, namespaceURI);
1864 if (!Document::hasValidNamespaceForAttributes(qName)) {
1873 void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1875 QualifiedName parsedName = anyName;
1876 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1878 setAttribute(parsedName, value);
1881 void Element::removeAttributeInternal(unsigned index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1883 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1885 UniqueElementData& elementData = ensureUniqueElementData();
1887 QualifiedName name = elementData.attributeAt(index).name();
1888 AtomicString valueBeingRemoved = elementData.attributeAt(index).value();
1890 if (!inSynchronizationOfLazyAttribute) {
1891 if (!valueBeingRemoved.isNull())
1892 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1895 if (RefPtr<Attr> attrNode = attrIfExists(name))
1896 detachAttrNodeFromElementWithValue(attrNode.get(), elementData.attributeAt(index).value());
1898 elementData.removeAttribute(index);
1900 if (!inSynchronizationOfLazyAttribute)
1901 didRemoveAttribute(name, valueBeingRemoved);
1904 void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1906 if (!inSynchronizationOfLazyAttribute)
1907 willModifyAttribute(name, nullAtom, value);
1908 ensureUniqueElementData().addAttribute(name, value);
1909 if (!inSynchronizationOfLazyAttribute)
1910 didAddAttribute(name, value);
1913 bool Element::removeAttribute(const AtomicString& name)
1918 AtomicString localName = shouldIgnoreAttributeCase(*this) ? name.convertToASCIILowercase() : name;
1919 unsigned index = elementData()->findAttributeIndexByName(localName, false);
1920 if (index == ElementData::attributeNotFound) {
1921 if (UNLIKELY(localName == styleAttr) && elementData()->styleAttributeIsDirty() && is<StyledElement>(*this))
1922 downcast<StyledElement>(*this).removeAllInlineStyleProperties();
1926 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1930 bool Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1932 return removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1935 RefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1939 synchronizeAttribute(localName);
1940 const Attribute* attribute = elementData()->findAttributeByName(localName, shouldIgnoreAttributeCase(*this));
1943 return ensureAttr(attribute->name());
1946 RefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1950 QualifiedName qName(nullAtom, localName, namespaceURI);
1951 synchronizeAttribute(qName);
1952 const Attribute* attribute = elementData()->findAttributeByName(qName);
1955 return ensureAttr(attribute->name());
1958 bool Element::hasAttribute(const AtomicString& localName) const
1962 synchronizeAttribute(localName);
1963 return elementData()->findAttributeByName(localName, shouldIgnoreAttributeCase(*this));
1966 bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1970 QualifiedName qName(nullAtom, localName, namespaceURI);
1971 synchronizeAttribute(qName);
1972 return elementData()->findAttributeByName(qName);
1975 CSSStyleDeclaration *Element::style()
1980 void Element::focus(bool restorePreviousSelection, FocusDirection direction)
1985 if (document().focusedElement() == this)
1988 // If the stylesheets have already been loaded we can reliably check isFocusable.
1989 // If not, we continue and set the focused node on the focus controller below so
1990 // that it can be updated soon after attach.
1991 if (document().haveStylesheetsLoaded()) {
1992 document().updateLayoutIgnorePendingStylesheets();
1997 if (!supportsFocus())
2000 RefPtr<Node> protect;
2001 if (Page* page = document().page()) {
2002 // Focus and change event handlers can cause us to lose our last ref.
2003 // If a focus event handler changes the focus to a different node it
2004 // does not make sense to continue and update appearence.
2006 if (!page->focusController().setFocusedElement(this, document().frame(), direction))
2010 // Setting the focused node above might have invalidated the layout due to scripts.
2011 document().updateLayoutIgnorePendingStylesheets();
2013 if (!isFocusable()) {
2014 ensureElementRareData().setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2018 cancelFocusAppearanceUpdate();
2020 // Focusing a form element triggers animation in UIKit to scroll to the right position.
2021 // Calling updateFocusAppearance() would generate an unnecessary call to ScrollView::setScrollPosition(),
2022 // which would jump us around during this animation. See <rdar://problem/6699741>.
2023 FrameView* view = document().view();
2024 bool isFormControl = view && is<HTMLFormControlElement>(*this);
2026 view->setProhibitsScrolling(true);
2028 updateFocusAppearance(restorePreviousSelection);
2031 view->setProhibitsScrolling(false);
2035 void Element::updateFocusAppearanceAfterAttachIfNeeded()
2039 ElementRareData* data = elementRareData();
2040 if (!data->needsFocusAppearanceUpdateSoonAfterAttach())
2042 if (isFocusable() && document().focusedElement() == this)
2043 document().updateFocusAppearanceSoon(false /* don't restore selection */);
2044 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2047 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2049 if (isRootEditableElement()) {
2050 Frame* frame = document().frame();
2054 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2055 if (this == frame->selection().selection().rootEditableElement())
2058 // FIXME: We should restore the previous selection if there is one.
2059 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
2061 if (frame->selection().shouldChangeSelection(newSelection)) {
2062 frame->selection().setSelection(newSelection);
2063 frame->selection().revealSelection();
2065 } else if (renderer() && !renderer()->isWidget())
2066 renderer()->scrollRectToVisible(renderer()->anchorRect());
2069 void Element::blur()
2071 cancelFocusAppearanceUpdate();
2072 if (treeScope().focusedElement() == this) {
2073 if (Frame* frame = document().frame())
2074 frame->page()->focusController().setFocusedElement(0, frame);
2076 document().setFocusedElement(0);
2080 void Element::dispatchFocusInEvent(const AtomicString& eventType, RefPtr<Element>&& oldFocusedElement)
2082 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2083 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2084 dispatchScopedEvent(FocusEvent::create(eventType, true, false, document().defaultView(), 0, WTF::move(oldFocusedElement)));
2087 void Element::dispatchFocusOutEvent(const AtomicString& eventType, RefPtr<Element>&& newFocusedElement)
2089 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2090 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2091 dispatchScopedEvent(FocusEvent::create(eventType, true, false, document().defaultView(), 0, WTF::move(newFocusedElement)));
2094 void Element::dispatchFocusEvent(RefPtr<Element>&& oldFocusedElement, FocusDirection)
2096 if (document().page())
2097 document().page()->chrome().client().elementDidFocus(this);
2099 EventDispatcher::dispatchEvent(this, FocusEvent::create(eventNames().focusEvent, false, false, document().defaultView(), 0, WTF::move(oldFocusedElement)));
2102 void Element::dispatchBlurEvent(RefPtr<Element>&& newFocusedElement)
2104 if (document().page())
2105 document().page()->chrome().client().elementDidBlur(this);
2107 EventDispatcher::dispatchEvent(this, FocusEvent::create(eventNames().blurEvent, false, false, document().defaultView(), 0, WTF::move(newFocusedElement)));
2110 void Element::mergeWithNextTextNode(Text& node, ExceptionCode& ec)
2112 Node* next = node.nextSibling();
2113 if (!is<Text>(next))
2116 Ref<Text> textNode(node);
2117 Ref<Text> textNext(downcast<Text>(*next));
2118 textNode->appendData(textNext->data(), ec);
2121 textNext->remove(ec);
2124 String Element::innerHTML() const
2126 return createMarkup(*this, ChildrenOnly);
2129 String Element::outerHTML() const
2131 return createMarkup(*this);
2134 void Element::setOuterHTML(const String& html, ExceptionCode& ec)
2136 Element* p = parentElement();
2137 if (!is<HTMLElement>(p)) {
2138 ec = NO_MODIFICATION_ALLOWED_ERR;
2141 RefPtr<HTMLElement> parent = downcast<HTMLElement>(p);
2142 RefPtr<Node> prev = previousSibling();
2143 RefPtr<Node> next = nextSibling();
2145 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, ec);
2149 parent->replaceChild(fragment.release(), this, ec);
2150 RefPtr<Node> node = next ? next->previousSibling() : nullptr;
2151 if (!ec && is<Text>(node.get()))
2152 mergeWithNextTextNode(downcast<Text>(*node), ec);
2153 if (!ec && is<Text>(prev.get()))
2154 mergeWithNextTextNode(downcast<Text>(*prev), ec);
2158 void Element::setInnerHTML(const String& html, ExceptionCode& ec)
2160 if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, ec)) {
2161 ContainerNode* container = this;
2163 #if ENABLE(TEMPLATE_ELEMENT)
2164 if (is<HTMLTemplateElement>(*this))
2165 container = downcast<HTMLTemplateElement>(*this).content();
2168 replaceChildrenWithFragment(*container, fragment.release(), ec);
2172 String Element::innerText()
2174 // We need to update layout, since plainText uses line boxes in the render tree.
2175 document().updateLayoutIgnorePendingStylesheets();
2178 return textContent(true);
2180 return plainText(rangeOfContents(*this).ptr());
2183 String Element::outerText()
2185 // Getting outerText is the same as getting innerText, only
2186 // setting is different. You would think this should get the plain
2187 // text for the outer range, but this is wrong, <br> for instance
2188 // would return different values for inner and outer text by such
2189 // a rule, but it doesn't in WinIE, and we want to match that.
2193 String Element::title() const
2198 const AtomicString& Element::pseudo() const
2200 return fastGetAttribute(pseudoAttr);
2203 void Element::setPseudo(const AtomicString& value)
2205 setAttributeWithoutSynchronization(pseudoAttr, value);
2208 LayoutSize Element::minimumSizeForResizing() const
2210 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2213 void Element::setMinimumSizeForResizing(const LayoutSize& size)
2215 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2217 ensureElementRareData().setMinimumSizeForResizing(size);
2220 static PseudoElement* beforeOrAfterPseudoElement(Element* host, PseudoId pseudoElementSpecifier)
2222 switch (pseudoElementSpecifier) {
2224 return host->beforePseudoElement();
2226 return host->afterPseudoElement();
2232 RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2234 if (PseudoElement* pseudoElement = beforeOrAfterPseudoElement(this, pseudoElementSpecifier))
2235 return pseudoElement->computedStyle();
2237 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2238 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2239 // values returned for the ":selection" pseudo-element will be correct.
2240 if (RenderStyle* usedStyle = renderStyle()) {
2241 if (pseudoElementSpecifier) {
2242 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2243 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2248 if (!inDocument()) {
2249 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2250 // document tree and figure out when to destroy the computed style for such elements.
2254 ElementRareData& data = ensureElementRareData();
2255 if (!data.computedStyle())
2256 data.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
2257 return pseudoElementSpecifier ? data.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data.computedStyle();
2260 void Element::setStyleAffectedByEmpty()
2262 ensureElementRareData().setStyleAffectedByEmpty(true);
2265 void Element::setChildrenAffectedByActive()
2267 ensureElementRareData().setChildrenAffectedByActive(true);
2270 void Element::setChildrenAffectedByDrag()
2272 ensureElementRareData().setChildrenAffectedByDrag(true);
2275 void Element::setChildrenAffectedByBackwardPositionalRules()
2277 ensureElementRareData().setChildrenAffectedByBackwardPositionalRules(true);
2280 void Element::setChildrenAffectedByPropertyBasedBackwardPositionalRules()
2282 ensureElementRareData().setChildrenAffectedByPropertyBasedBackwardPositionalRules(true);
2285 void Element::setChildIndex(unsigned index)
2287 ElementRareData& rareData = ensureElementRareData();
2288 if (RenderStyle* style = renderStyle())
2290 rareData.setChildIndex(index);
2293 bool Element::hasFlagsSetDuringStylingOfChildren() const
2295 if (childrenAffectedByHover() || childrenAffectedByFirstChildRules() || childrenAffectedByLastChildRules())
2300 return rareDataChildrenAffectedByActive()
2301 || rareDataChildrenAffectedByDrag()
2302 || rareDataChildrenAffectedByBackwardPositionalRules()
2303 || rareDataChildrenAffectedByPropertyBasedBackwardPositionalRules();
2306 bool Element::rareDataStyleAffectedByEmpty() const
2308 ASSERT(hasRareData());
2309 return elementRareData()->styleAffectedByEmpty();
2312 bool Element::rareDataChildrenAffectedByActive() const
2314 ASSERT(hasRareData());
2315 return elementRareData()->childrenAffectedByActive();
2318 bool Element::rareDataChildrenAffectedByDrag() const
2320 ASSERT(hasRareData());
2321 return elementRareData()->childrenAffectedByDrag();
2324 bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2326 ASSERT(hasRareData());
2327 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2330 bool Element::rareDataChildrenAffectedByPropertyBasedBackwardPositionalRules() const
2332 ASSERT(hasRareData());
2333 return elementRareData()->childrenAffectedByPropertyBasedBackwardPositionalRules();
2336 unsigned Element::rareDataChildIndex() const
2338 ASSERT(hasRareData());
2339 return elementRareData()->childIndex();
2342 void Element::setRegionOversetState(RegionOversetState state)
2344 ensureElementRareData().setRegionOversetState(state);
2347 RegionOversetState Element::regionOversetState() const
2349 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2352 AtomicString Element::computeInheritedLanguage() const
2354 if (const ElementData* elementData = this->elementData()) {
2355 if (const Attribute* attribute = elementData->findLanguageAttribute())
2356 return attribute->value();
2359 // The language property is inherited, so we iterate over the parents to find the first language.
2360 const Node* currentNode = this;
2361 while ((currentNode = currentNode->parentNode())) {
2362 if (is<Element>(*currentNode)) {
2363 if (const ElementData* elementData = downcast<Element>(*currentNode).elementData()) {
2364 if (const Attribute* attribute = elementData->findLanguageAttribute())
2365 return attribute->value();
2367 } else if (is<Document>(*currentNode)) {
2368 // checking the MIME content-language
2369 return downcast<Document>(*currentNode).contentLanguage();
2376 Locale& Element::locale() const
2378 return document().getCachedLocale(computeInheritedLanguage());
2381 void Element::cancelFocusAppearanceUpdate()
2384 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2385 if (document().focusedElement() == this)
2386 document().cancelFocusAppearanceUpdate();
2389 void Element::normalizeAttributes()
2391 if (!hasAttributes())
2394 auto* attrNodeList = attrNodeListForElement(*this);
2398 // Copy the Attr Vector because Node::normalize() can fire synchronous JS
2399 // events (e.g. DOMSubtreeModified) and a JS listener could add / remove
2400 // attributes while we are iterating.
2401 auto copyOfAttrNodeList = *attrNodeList;
2402 for (auto& attrNode : copyOfAttrNodeList)
2403 attrNode->normalize();
2406 PseudoElement* Element::beforePseudoElement() const
2408 return hasRareData() ? elementRareData()->beforePseudoElement() : 0;
2411 PseudoElement* Element::afterPseudoElement() const
2413 return hasRareData() ? elementRareData()->afterPseudoElement() : 0;
2416 void Element::setBeforePseudoElement(Ref<PseudoElement>&& element)
2418 ensureElementRareData().setBeforePseudoElement(WTF::move(element));
2421 void Element::setAfterPseudoElement(Ref<PseudoElement>&& element)
2423 ensureElementRareData().setAfterPseudoElement(WTF::move(element));
2426 static void disconnectPseudoElement(PseudoElement* pseudoElement)
2430 if (pseudoElement->renderer())
2431 Style::detachRenderTree(*pseudoElement);
2432 ASSERT(pseudoElement->hostElement());
2433 pseudoElement->clearHostElement();
2436 void Element::clearBeforePseudoElement()
2440 disconnectPseudoElement(elementRareData()->beforePseudoElement());
2441 elementRareData()->setBeforePseudoElement(nullptr);
2444 void Element::clearAfterPseudoElement()
2448 disconnectPseudoElement(elementRareData()->afterPseudoElement());
2449 elementRareData()->setAfterPseudoElement(nullptr);
2452 // ElementTraversal API
2453 Element* Element::firstElementChild() const
2455 return ElementTraversal::firstChild(*this);
2458 Element* Element::lastElementChild() const
2460 return ElementTraversal::lastChild(*this);
2463 Element* Element::previousElementSibling() const
2465 return ElementTraversal::previousSibling(*this);
2468 Element* Element::nextElementSibling() const
2470 return ElementTraversal::nextSibling(*this);
2473 unsigned Element::childElementCount() const
2476 Node* n = firstChild();
2478 count += n->isElementNode();
2479 n = n->nextSibling();
2484 bool Element::matchesReadWritePseudoClass() const
2489 bool Element::matches(const String& selector, ExceptionCode& ec)
2491 SelectorQuery* selectorQuery = document().selectorQueryForString(selector, ec);
2492 return selectorQuery && selectorQuery->matches(*this);
2495 Element* Element::closest(const String& selector, ExceptionCode& ec)
2497 SelectorQuery* selectorQuery = document().selectorQueryForString(selector, ec);
2499 return selectorQuery->closest(*this);
2503 bool Element::shouldAppearIndeterminate() const
2508 bool Element::mayCauseRepaintInsideViewport(const IntRect* visibleRect) const
2510 return renderer() && renderer()->mayCauseRepaintInsideViewport(visibleRect);
2513 DOMTokenList& Element::classList()
2515 ElementRareData& data = ensureElementRareData();
2516 if (!data.classList())
2517 data.setClassList(std::make_unique<ClassList>(*this));
2518 return *data.classList();
2521 DatasetDOMStringMap& Element::dataset()
2523 ElementRareData& data = ensureElementRareData();
2524 if (!data.dataset())
2525 data.setDataset(std::make_unique<DatasetDOMStringMap>(*this));
2526 return *data.dataset();
2529 URL Element::getURLAttribute(const QualifiedName& name) const
2531 #if !ASSERT_DISABLED
2532 if (elementData()) {
2533 if (const Attribute* attribute = findAttributeByName(name))
2534 ASSERT(isURLAttribute(*attribute));
2537 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2540 URL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2542 #if !ASSERT_DISABLED
2543 if (elementData()) {
2544 if (const Attribute* attribute = findAttributeByName(name))
2545 ASSERT(isURLAttribute(*attribute));
2548 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2549 if (value.isEmpty())
2551 return document().completeURL(value);
2554 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2556 return getAttribute(attributeName).string().toInt();
2559 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2561 setAttribute(attributeName, AtomicString::number(value));
2564 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2566 return getAttribute(attributeName).string().toUInt();
2569 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2571 setAttribute(attributeName, AtomicString::number(value));
2574 #if ENABLE(INDIE_UI)
2575 void Element::setUIActions(const AtomicString& actions)
2577 setAttribute(uiactionsAttr, actions);
2580 const AtomicString& Element::UIActions() const
2582 return getAttribute(uiactionsAttr);
2586 bool Element::childShouldCreateRenderer(const Node& child) const
2588 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2589 if (child.isSVGElement()) {
2590 ASSERT(!isSVGElement());
2591 const SVGElement& childElement = downcast<SVGElement>(child);
2592 return is<SVGSVGElement>(childElement) && childElement.isValid();
2597 #if ENABLE(FULLSCREEN_API)
2598 void Element::webkitRequestFullscreen()
2600 document().requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, Document::EnforceIFrameAllowFullScreenRequirement);
2603 void Element::webkitRequestFullScreen(unsigned short flags)
2605 document().requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), Document::EnforceIFrameAllowFullScreenRequirement);
2608 bool Element::containsFullScreenElement() const
2610 return hasRareData() && elementRareData()->containsFullScreenElement();
2613 void Element::setContainsFullScreenElement(bool flag)
2615 ensureElementRareData().setContainsFullScreenElement(flag);
2616 setNeedsStyleRecalc(SyntheticStyleChange);
2619 static Element* parentCrossingFrameBoundaries(Element* element)
2622 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
2625 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2627 Element* element = this;
2628 while ((element = parentCrossingFrameBoundaries(element)))
2629 element->setContainsFullScreenElement(flag);
2633 #if ENABLE(POINTER_LOCK)
2634 void Element::requestPointerLock()
2636 if (document().page())
2637 document().page()->pointerLockController().requestPointerLock(this);
2641 SpellcheckAttributeState Element::spellcheckAttributeState() const
2643 const AtomicString& value = fastGetAttribute(HTMLNames::spellcheckAttr);
2644 if (value == nullAtom)
2645 return SpellcheckAttributeDefault;
2646 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2647 return SpellcheckAttributeTrue;
2648 if (equalIgnoringCase(value, "false"))
2649 return SpellcheckAttributeFalse;
2651 return SpellcheckAttributeDefault;
2654 bool Element::isSpellCheckingEnabled() const
2656 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2657 switch (element->spellcheckAttributeState()) {
2658 case SpellcheckAttributeTrue:
2660 case SpellcheckAttributeFalse:
2662 case SpellcheckAttributeDefault:
2670 RenderNamedFlowFragment* Element::renderNamedFlowFragment() const
2672 if (renderer() && renderer()->isRenderNamedFlowFragmentContainer())
2673 return downcast<RenderBlockFlow>(*renderer()).renderNamedFlowFragment();
2678 #if ENABLE(CSS_REGIONS)
2680 bool Element::shouldMoveToFlowThread(const RenderStyle& styleToUse) const
2682 #if ENABLE(FULLSCREEN_API)
2683 if (document().webkitIsFullScreen() && document().webkitCurrentFullScreenElement() == this)
2687 if (isInShadowTree())
2690 if (!styleToUse.hasFlowInto())
2696 const AtomicString& Element::webkitRegionOverset() const
2698 document().updateLayoutIgnorePendingStylesheets();
2700 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2701 if (!document().cssRegionsEnabled() || !renderNamedFlowFragment())
2702 return undefinedState;
2704 switch (regionOversetState()) {
2706 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2710 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2713 case RegionOverset: {
2714 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2715 return overflowState;
2717 case RegionUndefined:
2718 return undefinedState;
2721 ASSERT_NOT_REACHED();
2722 return undefinedState;
2725 Vector<RefPtr<Range>> Element::webkitGetRegionFlowRanges() const
2727 Vector<RefPtr<Range>> rangeObjects;
2728 if (!document().cssRegionsEnabled())
2729 return rangeObjects;
2731 document().updateLayoutIgnorePendingStylesheets();
2732 if (renderer() && renderer()->isRenderNamedFlowFragmentContainer()) {
2733 RenderNamedFlowFragment& namedFlowFragment = *downcast<RenderBlockFlow>(*renderer()).renderNamedFlowFragment();
2734 if (namedFlowFragment.isValid())
2735 namedFlowFragment.getRanges(rangeObjects);
2738 return rangeObjects;
2744 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2746 if (name == HTMLNames::styleAttr)
2750 return !downcast<SVGElement>(*this).isAnimatableAttribute(name);
2756 #ifdef DUMP_NODE_STATISTICS
2757 bool Element::hasNamedNodeMap() const
2759 return hasRareData() && elementRareData()->attributeMap();
2763 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2765 if (!isInTreeScope())
2768 if (oldName == newName)
2771 updateNameForTreeScope(treeScope(), oldName, newName);
2775 if (!is<HTMLDocument>(document()))
2777 updateNameForDocument(downcast<HTMLDocument>(document()), oldName, newName);
2780 void Element::updateNameForTreeScope(TreeScope& scope, const AtomicString& oldName, const AtomicString& newName)
2782 ASSERT(oldName != newName);
2784 if (!oldName.isEmpty())
2785 scope.removeElementByName(*oldName.impl(), *this);
2786 if (!newName.isEmpty())
2787 scope.addElementByName(*newName.impl(), *this);
2790 void Element::updateNameForDocument(HTMLDocument& document, const AtomicString& oldName, const AtomicString& newName)
2792 ASSERT(oldName != newName);
2794 if (WindowNameCollection::elementMatchesIfNameAttributeMatch(*this)) {
2795 const AtomicString& id = WindowNameCollection::elementMatchesIfIdAttributeMatch(*this) ? getIdAttribute() : nullAtom;
2796 if (!oldName.isEmpty() && oldName != id)
2797 document.removeWindowNamedItem(*oldName.impl(), *this);
2798 if (!newName.isEmpty() && newName != id)
2799 document.addWindowNamedItem(*newName.impl(), *this);
2802 if (DocumentNameCollection::elementMatchesIfNameAttributeMatch(*this)) {
2803 const AtomicString& id = DocumentNameCollection::elementMatchesIfIdAttributeMatch(*this) ? getIdAttribute() : nullAtom;
2804 if (!oldName.isEmpty() && oldName != id)
2805 document.removeDocumentNamedItem(*oldName.impl(), *this);
2806 if (!newName.isEmpty() && newName != id)
2807 document.addDocumentNamedItem(*newName.impl(), *this);
2811 inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2813 if (!isInTreeScope())
2819 updateIdForTreeScope(treeScope(), oldId, newId);
2823 if (!is<HTMLDocument>(document()))
2825 updateIdForDocument(downcast<HTMLDocument>(document()), oldId, newId, UpdateHTMLDocumentNamedItemMapsOnlyIfDiffersFromNameAttribute);
2828 void Element::updateIdForTreeScope(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
2830 ASSERT(isInTreeScope());
2831 ASSERT(oldId != newId);
2833 if (!oldId.isEmpty())
2834 scope.removeElementById(*oldId.impl(), *this);
2835 if (!newId.isEmpty())
2836 scope.addElementById(*newId.impl(), *this);
2839 void Element::updateIdForDocument(HTMLDocument& document, const AtomicString& oldId, const AtomicString& newId, HTMLDocumentNamedItemMapsUpdatingCondition condition)
2841 ASSERT(inDocument());
2842 ASSERT(oldId != newId);
2844 if (WindowNameCollection::elementMatchesIfIdAttributeMatch(*this)) {
2845 const AtomicString& name = condition == UpdateHTMLDocumentNamedItemMapsOnlyIfDiffersFromNameAttribute && WindowNameCollection::elementMatchesIfNameAttributeMatch(*this) ? getNameAttribute() : nullAtom;
2846 if (!oldId.isEmpty() && oldId != name)
2847 document.removeWindowNamedItem(*oldId.impl(), *this);
2848 if (!newId.isEmpty() && newId != name)
2849 document.addWindowNamedItem(*newId.impl(), *this);
2852 if (DocumentNameCollection::elementMatchesIfIdAttributeMatch(*this)) {
2853 const AtomicString& name = condition == UpdateHTMLDocumentNamedItemMapsOnlyIfDiffersFromNameAttribute && DocumentNameCollection::elementMatchesIfNameAttributeMatch(*this) ? getNameAttribute() : nullAtom;
2854 if (!oldId.isEmpty() && oldId != name)
2855 document.removeDocumentNamedItem(*oldId.impl(), *this);
2856 if (!newId.isEmpty() && newId != name)
2857 document.addDocumentNamedItem(*newId.impl(), *this);
2861 void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2863 ASSERT(hasTagName(labelTag));
2868 if (oldForAttributeValue == newForAttributeValue)
2871 if (!oldForAttributeValue.isEmpty())
2872 scope.removeLabel(*oldForAttributeValue.impl(), downcast<HTMLLabelElement>(*this));
2873 if (!newForAttributeValue.isEmpty())
2874 scope.addLabel(*newForAttributeValue.impl(), downcast<HTMLLabelElement>(*this));
2877 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2879 if (name == HTMLNames::idAttr)
2880 updateId(oldValue, newValue);
2881 else if (name == HTMLNames::nameAttr)
2882 updateName(oldValue, newValue);
2883 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2884 if (treeScope().shouldCacheLabelsByForAttribute())
2885 updateLabel(treeScope(), oldValue, newValue);
2888 if (oldValue != newValue) {
2889 auto styleResolver = document().styleResolverIfExists();
2890 if (styleResolver && styleResolver->hasSelectorForAttribute(*this, name.localName()))
2891 setNeedsStyleRecalc();
2894 if (std::unique_ptr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
2895 recipients->enqueueMutationRecord(MutationRecord::createAttributes(*this, name, oldValue));
2897 InspectorInstrumentation::willModifyDOMAttr(document(), *this, oldValue, newValue);
2900 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2902 attributeChanged(name, nullAtom, value);
2903 InspectorInstrumentation::didModifyDOMAttr(document(), *this, name.localName(), value);
2904 dispatchSubtreeModifiedEvent();
2907 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2909 attributeChanged(name, oldValue, newValue);
2910 InspectorInstrumentation::didModifyDOMAttr(document(), *this, name.localName(), newValue);
2911 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2914 void Element::didRemoveAttribute(const QualifiedName& name, const AtomicString& oldValue)
2916 attributeChanged(name, oldValue, nullAtom);
2917 InspectorInstrumentation::didRemoveDOMAttr(document(), *this, name.localName());
2918 dispatchSubtreeModifiedEvent();
2921 Ref<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2923 if (HTMLCollection* collection = cachedHTMLCollection(type))
2926 if (type == TableRows) {
2927 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLTableRowsCollection>(downcast<HTMLTableElement>(*this), type);
2928 } else if (type == SelectOptions) {
2929 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLOptionsCollection>(downcast<HTMLSelectElement>(*this), type);
2930 } else if (type == FormControls) {
2931 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2932 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLFormControlsCollection>(*this, type);
2934 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLCollection>(*this, type);
2937 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2939 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cachedCollection<HTMLCollection>(type) : 0;
2942 IntSize Element::savedLayerScrollOffset() const
2944 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2947 void Element::setSavedLayerScrollOffset(const IntSize& size)
2949 if (size.isZero() && !hasRareData())
2951 ensureElementRareData().setSavedLayerScrollOffset(size);
2954 RefPtr<Attr> Element::attrIfExists(const AtomicString& localName, bool shouldIgnoreAttributeCase)
2956 if (auto* attrNodeList = attrNodeListForElement(*this))
2957 return findAttrNodeInList(*attrNodeList, localName, shouldIgnoreAttributeCase);
2961 RefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2963 if (auto* attrNodeList = attrNodeListForElement(*this))
2964 return findAttrNodeInList(*attrNodeList, name);
2968 RefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2970 auto& attrNodeList = ensureAttrNodeListForElement(*this);
2971 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2973 attrNode = Attr::create(this, name);
2974 treeScope().adoptIfNeeded(attrNode.get());
2975 attrNodeList.append(attrNode);
2977 return attrNode.release();
2980 void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2982 ASSERT(hasSyntheticAttrChildNodes());
2983 attrNode->detachFromElementWithValue(value);
2985 auto& attrNodeList = *attrNodeListForElement(*this);
2986 bool found = attrNodeList.removeFirstMatching([attrNode] (const RefPtr<Attr>& attribute) {
2987 return attribute->qualifiedName() == attrNode->qualifiedName();
2989 ASSERT_UNUSED(found, found);
2990 if (attrNodeList.isEmpty())
2991 removeAttrNodeListForElement(*this);
2994 void Element::detachAllAttrNodesFromElement()
2996 auto* attrNodeList = attrNodeListForElement(*this);
2997 ASSERT(attrNodeList);
2999 for (const Attribute& attribute : attributesIterator()) {
3000 if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute.name()))
3001 attrNode->detachFromElementWithValue(attribute.value());
3004 removeAttrNodeListForElement(*this);
3007 void Element::resetComputedStyle()
3009 if (!hasRareData() || !elementRareData()->computedStyle())
3012 auto reset = [](Element& element) {
3013 if (!element.hasRareData() || !element.elementRareData()->computedStyle())
3015 if (element.hasCustomStyleResolveCallbacks())
3016 element.willResetComputedStyle();
3017 element.elementRareData()->resetComputedStyle();
3020 for (auto& child : descendantsOfType<Element>(*this))
3024 void Element::clearStyleDerivedDataBeforeDetachingRenderer()
3026 unregisterNamedFlowContentElement();
3027 cancelFocusAppearanceUpdate();
3028 clearBeforePseudoElement();
3029 clearAfterPseudoElement();
3032 ElementRareData* data = elementRareData();
3033 data->resetComputedStyle();
3034 data->resetDynamicRestyleObservations();
3037 void Element::clearHoverAndActiveStatusBeforeDetachingRenderer()
3039 if (!isUserActionElement())
3042 document().hoveredElementDidDetach(this);
3043 if (inActiveChain())
3044 document().elementInActiveChainDidDetach(this);
3045 document().userActionElements().didDetach(this);
3048 bool Element::willRecalcStyle(Style::Change)
3050 ASSERT(hasCustomStyleResolveCallbacks());
3054 void Element::didRecalcStyle(Style::Change)
3056 ASSERT(hasCustomStyleResolveCallbacks());
3059 void Element::willResetComputedStyle()
3061 ASSERT(hasCustomStyleResolveCallbacks());
3064 void Element::willAttachRenderers()
3066 ASSERT(hasCustomStyleResolveCallbacks());
3069 void Element::didAttachRenderers()
3071 ASSERT(hasCustomStyleResolveCallbacks());
3074 void Element::willDetachRenderers()
3076 ASSERT(hasCustomStyleResolveCallbacks());
3079 void Element::didDetachRenderers()
3081 ASSERT(hasCustomStyleResolveCallbacks());
3084 RefPtr<RenderStyle> Element::customStyleForRenderer(RenderStyle&)
3086 ASSERT(hasCustomStyleResolveCallbacks());
3090 void Element::cloneAttributesFromElement(const Element& other)
3092 if (hasSyntheticAttrChildNodes())
3093 detachAllAttrNodesFromElement();
3095 other.synchronizeAllAttributes();
3096 if (!other.m_elementData) {
3097 m_elementData.clear();
3101 // We can't update window and document's named item maps since the presence of image and object elements depend on other attributes and children.
3102 // Fortunately, those named item maps are only updated when this element is in the document, which should never be the case.
3103 ASSERT(!inDocument());
3105 const AtomicString& oldID = getIdAttribute();
3106 const AtomicString& newID = other.getIdAttribute();
3108 if (!oldID.isNull() || !newID.isNull())
3109 updateId(oldID, newID);
3111 const AtomicString& oldName = getNameAttribute();
3112 const AtomicString& newName = other.getNameAttribute();
3114 if (!oldName.isNull() || !newName.isNull())
3115 updateName(oldName, newName);
3117 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
3118 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes.
3119 if (is<UniqueElementData>(*other.m_elementData)
3120 && !other.m_elementData->presentationAttributeStyle()
3121 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3122 const_cast<Element&>(other).m_elementData = downcast<UniqueElementData>(*other.m_elementData).makeShareableCopy();
3124 if (!other.m_elementData->isUnique())
3125 m_elementData = other.m_elementData;
3127 m_elementData = other.m_elementData->makeUniqueCopy();
3129 for (const Attribute& attribute : attributesIterator())
3130 attributeChanged(attribute.name(), nullAtom, attribute.value(), ModifiedByCloning);
3133 void Element::cloneDataFromElement(const Element& other)
3135 cloneAttributesFromElement(other);
3136 copyNonAttributePropertiesFromElement(other);
3139 void Element::createUniqueElementData()
3142 m_elementData = UniqueElementData::create();
3144 m_elementData = downcast<ShareableElementData>(*m_elementData).makeUniqueCopy();
3147 bool Element::hasPendingResources() const
3149 return hasRareData() && elementRareData()->hasPendingResources();
3152 void Element::setHasPendingResources()
3154 ensureElementRareData().setHasPendingResources(true);
3157 void Element::clearHasPendingResources()
3159 ensureElementRareData().setHasPendingResources(false);
3162 bool Element::canContainRangeEndPoint() const
3164 return !equalIgnoringCase(fastGetAttribute(roleAttr), "img");
3167 String Element::completeURLsInAttributeValue(const URL& base, const Attribute& attribute) const
3169 return URL(base, attribute.value()).string();
3172 } // namespace WebCore