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 "FlowThreadController.h"
43 #include "FocusController.h"
44 #include "FocusEvent.h"
45 #include "FrameSelection.h"
46 #include "FrameView.h"
47 #include "HTMLCanvasElement.h"
48 #include "HTMLCollection.h"
49 #include "HTMLDocument.h"
50 #include "HTMLFormControlsCollection.h"
51 #include "HTMLLabelElement.h"
52 #include "HTMLNameCollection.h"
53 #include "HTMLOptionsCollection.h"
54 #include "HTMLParserIdioms.h"
55 #include "HTMLSelectElement.h"
56 #include "HTMLTableRowsCollection.h"
57 #include "InsertionPoint.h"
58 #include "KeyboardEvent.h"
59 #include "MutationObserverInterestGroup.h"
60 #include "MutationRecord.h"
61 #include "NodeRenderStyle.h"
62 #include "PlatformWheelEvent.h"
63 #include "PointerLockController.h"
64 #include "RenderLayer.h"
65 #include "RenderNamedFlowFragment.h"
66 #include "RenderRegion.h"
67 #include "RenderTheme.h"
68 #include "RenderView.h"
69 #include "RenderWidget.h"
70 #include "SVGDocumentExtensions.h"
71 #include "SVGElement.h"
73 #include "SelectorQuery.h"
75 #include "StyleProperties.h"
76 #include "StyleResolver.h"
77 #include "TextIterator.h"
78 #include "VoidCallback.h"
79 #include "WheelEvent.h"
80 #include "XLinkNames.h"
81 #include "XMLNSNames.h"
83 #include "htmlediting.h"
84 #include <wtf/BitVector.h>
85 #include <wtf/CurrentTime.h>
86 #include <wtf/text/CString.h>
90 using namespace HTMLNames;
91 using namespace XMLNames;
93 static inline bool shouldIgnoreAttributeCase(const Element& element)
95 return element.isHTMLElement() && element.document().isHTMLDocument();
98 static HashMap<Element*, Vector<RefPtr<Attr>>>& attrNodeListMap()
100 static NeverDestroyed<HashMap<Element*, Vector<RefPtr<Attr>>>> map;
104 static Vector<RefPtr<Attr>>* attrNodeListForElement(Element& element)
106 if (!element.hasSyntheticAttrChildNodes())
108 ASSERT(attrNodeListMap().contains(&element));
109 return &attrNodeListMap().find(&element)->value;
112 static Vector<RefPtr<Attr>>& ensureAttrNodeListForElement(Element& element)
114 if (element.hasSyntheticAttrChildNodes()) {
115 ASSERT(attrNodeListMap().contains(&element));
116 return attrNodeListMap().find(&element)->value;
118 ASSERT(!attrNodeListMap().contains(&element));
119 element.setHasSyntheticAttrChildNodes(true);
120 return attrNodeListMap().add(&element, Vector<RefPtr<Attr>>()).iterator->value;
123 static void removeAttrNodeListForElement(Element& element)
125 ASSERT(element.hasSyntheticAttrChildNodes());
126 ASSERT(attrNodeListMap().contains(&element));
127 attrNodeListMap().remove(&element);
128 element.setHasSyntheticAttrChildNodes(false);
131 static Attr* findAttrNodeInList(Vector<RefPtr<Attr>>& attrNodeList, const QualifiedName& name)
133 for (auto& node : attrNodeList) {
134 if (node->qualifiedName() == name)
140 PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document& document)
142 return adoptRef(new Element(tagName, document, CreateElement));
145 Element::Element(const QualifiedName& tagName, Document& document, ConstructionType type)
146 : ContainerNode(document, type)
154 if (document().hasLivingRenderTree()) {
155 // When the document is not destroyed, an element that was part of a named flow
156 // content nodes should have been removed from the content nodes collection
157 // and the isNamedFlowContentNode flag reset.
158 ASSERT_WITH_SECURITY_IMPLICATION(!isNamedFlowContentNode());
162 ASSERT(!beforePseudoElement());
163 ASSERT(!afterPseudoElement());
167 if (hasSyntheticAttrChildNodes())
168 detachAllAttrNodesFromElement();
170 if (hasPendingResources()) {
171 document().accessSVGExtensions().removeElementFromPendingResources(this);
172 ASSERT(!hasPendingResources());
176 inline ElementRareData* Element::elementRareData() const
178 ASSERT_WITH_SECURITY_IMPLICATION(hasRareData());
179 return static_cast<ElementRareData*>(rareData());
182 inline ElementRareData& Element::ensureElementRareData()
184 return static_cast<ElementRareData&>(ensureRareData());
187 void Element::clearTabIndexExplicitlyIfNeeded()
190 elementRareData()->clearTabIndexExplicitly();
193 void Element::setTabIndexExplicitly(short tabIndex)
195 ensureElementRareData().setTabIndexExplicitly(tabIndex);
198 bool Element::supportsFocus() const
200 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
203 Element* Element::focusDelegate()
208 short Element::tabIndex() const
210 return hasRareData() ? elementRareData()->tabIndex() : 0;
213 void Element::setTabIndex(int value)
215 setIntegralAttribute(tabindexAttr, value);
218 bool Element::isKeyboardFocusable(KeyboardEvent*) const
220 return isFocusable() && tabIndex() >= 0;
223 bool Element::isMouseFocusable() const
225 return isFocusable();
228 bool Element::shouldUseInputMethod()
230 return isContentEditable(UserSelectAllIsAlwaysNonEditable);
233 bool Element::dispatchMouseEvent(const PlatformMouseEvent& platformEvent, const AtomicString& eventType, int detail, Element* relatedTarget)
235 if (isDisabledFormControl())
238 RefPtr<MouseEvent> mouseEvent = MouseEvent::create(eventType, document().defaultView(), platformEvent, detail, relatedTarget);
240 if (mouseEvent->type().isEmpty())
241 return true; // Shouldn't happen.
243 ASSERT(!mouseEvent->target() || mouseEvent->target() != relatedTarget);
244 bool didNotSwallowEvent = dispatchEvent(mouseEvent) && !mouseEvent->defaultHandled();
246 if (mouseEvent->type() == eventNames().clickEvent && mouseEvent->detail() == 2) {
247 // Special case: If it's a double click event, we also send the dblclick event. This is not part
248 // of the DOM specs, but is used for compatibility with the ondblclick="" attribute. This is treated
249 // as a separate event in other DOM-compliant browsers like Firefox, and so we do the same.
250 RefPtr<MouseEvent> doubleClickEvent = MouseEvent::create();
251 doubleClickEvent->initMouseEvent(eventNames().dblclickEvent,
252 mouseEvent->bubbles(), mouseEvent->cancelable(), mouseEvent->view(), mouseEvent->detail(),
253 mouseEvent->screenX(), mouseEvent->screenY(), mouseEvent->clientX(), mouseEvent->clientY(),
254 mouseEvent->ctrlKey(), mouseEvent->altKey(), mouseEvent->shiftKey(), mouseEvent->metaKey(),
255 mouseEvent->button(), relatedTarget);
257 if (mouseEvent->defaultHandled())
258 doubleClickEvent->setDefaultHandled();
260 dispatchEvent(doubleClickEvent);
261 if (doubleClickEvent->defaultHandled() || doubleClickEvent->defaultPrevented())
264 return didNotSwallowEvent;
268 bool Element::dispatchWheelEvent(const PlatformWheelEvent& event)
270 RefPtr<WheelEvent> wheelEvent = WheelEvent::create(event, document().defaultView());
271 return EventDispatcher::dispatchEvent(this, wheelEvent) && !wheelEvent->defaultHandled();
274 bool Element::dispatchKeyEvent(const PlatformKeyboardEvent& platformEvent)
276 RefPtr<KeyboardEvent> event = KeyboardEvent::create(platformEvent, document().defaultView());
277 return EventDispatcher::dispatchEvent(this, event) && !event->defaultHandled();
280 void Element::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
282 EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions, visualOptions);
285 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
286 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
287 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
288 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
290 PassRefPtr<Node> Element::cloneNode(bool deep)
292 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
295 PassRefPtr<Element> Element::cloneElementWithChildren()
297 RefPtr<Element> clone = cloneElementWithoutChildren();
298 cloneChildNodes(clone.get());
299 return clone.release();
302 PassRefPtr<Element> Element::cloneElementWithoutChildren()
304 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
305 // This will catch HTML elements in the wrong namespace that are not correctly copied.
306 // This is a sanity check as HTML overloads some of the DOM methods.
307 ASSERT(isHTMLElement() == clone->isHTMLElement());
309 clone->cloneDataFromElement(*this);
310 return clone.release();
313 PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
315 return document().createElement(tagQName(), false);
318 PassRefPtr<Attr> Element::detachAttribute(unsigned index)
320 ASSERT(elementData());
322 const Attribute& attribute = elementData()->attributeAt(index);
324 RefPtr<Attr> attrNode = attrIfExists(attribute.name());
326 detachAttrNodeFromElementWithValue(attrNode.get(), attribute.value());
328 attrNode = Attr::create(document(), attribute.name(), attribute.value());
330 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
331 return attrNode.release();
334 bool Element::removeAttribute(const QualifiedName& name)
339 unsigned index = elementData()->findAttributeIndexByName(name);
340 if (index == ElementData::attributeNotFound)
343 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
347 void Element::setBooleanAttribute(const QualifiedName& name, bool value)
350 setAttribute(name, emptyAtom);
352 removeAttribute(name);
355 NamedNodeMap* Element::attributes() const
357 ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
358 if (NamedNodeMap* attributeMap = rareData.attributeMap())
361 rareData.setAttributeMap(NamedNodeMap::create(const_cast<Element&>(*this)));
362 return rareData.attributeMap();
365 Node::NodeType Element::nodeType() const
370 bool Element::hasAttribute(const QualifiedName& name) const
372 return hasAttributeNS(name.namespaceURI(), name.localName());
375 void Element::synchronizeAllAttributes() const
379 if (elementData()->styleAttributeIsDirty()) {
380 ASSERT(isStyledElement());
381 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
384 if (elementData()->animatedSVGAttributesAreDirty()) {
385 ASSERT(isSVGElement());
386 downcast<SVGElement>(*this).synchronizeAnimatedSVGAttribute(anyQName());
390 ALWAYS_INLINE void Element::synchronizeAttribute(const QualifiedName& name) const
394 if (UNLIKELY(name == styleAttr && elementData()->styleAttributeIsDirty())) {
395 ASSERT_WITH_SECURITY_IMPLICATION(isStyledElement());
396 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
400 if (UNLIKELY(elementData()->animatedSVGAttributesAreDirty())) {
401 ASSERT(isSVGElement());
402 downcast<SVGElement>(*this).synchronizeAnimatedSVGAttribute(name);
406 ALWAYS_INLINE void Element::synchronizeAttribute(const AtomicString& localName) const
408 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
409 // e.g when called from DOM API.
412 if (elementData()->styleAttributeIsDirty() && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(*this))) {
413 ASSERT_WITH_SECURITY_IMPLICATION(isStyledElement());
414 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
418 if (elementData()->animatedSVGAttributesAreDirty()) {
419 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
420 ASSERT_WITH_SECURITY_IMPLICATION(isSVGElement());
421 downcast<SVGElement>(*this).synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
425 const AtomicString& Element::getAttribute(const QualifiedName& name) const
429 synchronizeAttribute(name);
430 if (const Attribute* attribute = findAttributeByName(name))
431 return attribute->value();
435 bool Element::isFocusable() const
437 if (!inDocument() || !supportsFocus())
441 // If the node is in a display:none tree it might say it needs style recalc but
442 // the whole document is actually up to date.
443 ASSERT(!needsStyleRecalc() || !document().childNeedsStyleRecalc());
445 // Elements in canvas fallback content are not rendered, but they are allowed to be
446 // focusable as long as their canvas is displayed and visible.
447 if (auto* canvas = ancestorsOfType<HTMLCanvasElement>(*this).first())
448 return canvas->renderer() && canvas->renderer()->style().visibility() == VISIBLE;
451 // FIXME: Even if we are not visible, we might have a child that is visible.
452 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
453 if (!renderer() || renderer()->style().visibility() != VISIBLE)
459 bool Element::isUserActionElementInActiveChain() const
461 ASSERT(isUserActionElement());
462 return document().userActionElements().isInActiveChain(this);
465 bool Element::isUserActionElementActive() const
467 ASSERT(isUserActionElement());
468 return document().userActionElements().isActive(this);
471 bool Element::isUserActionElementFocused() const
473 ASSERT(isUserActionElement());
474 return document().userActionElements().isFocused(this);
477 bool Element::isUserActionElementHovered() const
479 ASSERT(isUserActionElement());
480 return document().userActionElements().isHovered(this);
483 void Element::setActive(bool flag, bool pause)
485 if (flag == active())
488 document().userActionElements().setActive(this, flag);
493 bool reactsToPress = renderStyle()->affectedByActive() || childrenAffectedByActive();
495 setNeedsStyleRecalc();
497 if (renderer()->style().hasAppearance() && renderer()->theme().stateChanged(*renderer(), ControlStates::PressedState))
498 reactsToPress = true;
500 // The rest of this function implements a feature that only works if the
501 // platform supports immediate invalidations on the ChromeClient, so bail if
502 // that isn't supported.
503 if (!document().page()->chrome().client().supportsImmediateInvalidation())
506 if (reactsToPress && pause) {
507 // The delay here is subtle. It relies on an assumption, namely that the amount of time it takes
508 // to repaint the "down" state of the control is about the same time as it would take to repaint the
509 // "up" state. Once you assume this, you can just delay for 100ms - that time (assuming that after you
510 // leave this method, it will be about that long before the flush of the up state happens again).
511 #ifdef HAVE_FUNC_USLEEP
512 double startTime = monotonicallyIncreasingTime();
515 document().updateStyleIfNeeded();
517 // Do an immediate repaint.
519 renderer()->repaint();
521 // FIXME: Come up with a less ridiculous way of doing this.
522 #ifdef HAVE_FUNC_USLEEP
523 // Now pause for a small amount of time (1/10th of a second from before we repainted in the pressed state)
524 double remainingTime = 0.1 - (monotonicallyIncreasingTime() - startTime);
525 if (remainingTime > 0)
526 usleep(static_cast<useconds_t>(remainingTime * 1000000.0));
531 void Element::setFocus(bool flag)
533 if (flag == focused())
536 document().userActionElements().setFocused(this, flag);
537 setNeedsStyleRecalc();
540 void Element::setHovered(bool flag)
542 if (flag == hovered())
545 document().userActionElements().setHovered(this, flag);
548 // When setting hover to false, the style needs to be recalc'd even when
549 // there's no renderer (imagine setting display:none in the :hover class,
550 // if a nil renderer would prevent this element from recalculating its
551 // style, it would never go back to its normal style and remain
552 // stuck in its hovered style).
554 setNeedsStyleRecalc();
559 if (renderer()->style().affectedByHover() || childrenAffectedByHover())
560 setNeedsStyleRecalc();
562 if (renderer()->style().hasAppearance())
563 renderer()->theme().stateChanged(*renderer(), ControlStates::HoverState);
566 void Element::scrollIntoView(bool alignToTop)
568 document().updateLayoutIgnorePendingStylesheets();
573 LayoutRect bounds = boundingBox();
574 // Align to the top / bottom and to the closest edge.
576 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
578 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
581 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
583 document().updateLayoutIgnorePendingStylesheets();
588 LayoutRect bounds = boundingBox();
590 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
592 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
595 void Element::scrollByUnits(int units, ScrollGranularity granularity)
597 document().updateLayoutIgnorePendingStylesheets();
602 if (!renderer()->hasOverflowClip())
605 ScrollDirection direction = ScrollDown;
607 direction = ScrollUp;
610 Element* stopElement = this;
611 toRenderBox(renderer())->scroll(direction, granularity, units, &stopElement);
614 void Element::scrollByLines(int lines)
616 scrollByUnits(lines, ScrollByLine);
619 void Element::scrollByPages(int pages)
621 scrollByUnits(pages, ScrollByPage);
624 static double localZoomForRenderer(const RenderElement& renderer)
626 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
627 // other out, but the alternative is that we'd have to crawl up the whole render tree every
628 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
629 double zoomFactor = 1;
630 if (renderer.style().effectiveZoom() != 1) {
631 // Need to find the nearest enclosing RenderElement that set up
632 // a differing zoom, and then we divide our result by it to eliminate the zoom.
633 const RenderElement* prev = &renderer;
634 for (RenderElement* curr = prev->parent(); curr; curr = curr->parent()) {
635 if (curr->style().effectiveZoom() != prev->style().effectiveZoom()) {
636 zoomFactor = prev->style().zoom();
641 if (prev->isRenderView())
642 zoomFactor = prev->style().zoom();
647 static double adjustForLocalZoom(LayoutUnit value, const RenderElement& renderer, double& zoomFactor)
649 zoomFactor = localZoomForRenderer(renderer);
651 return value.toDouble();
652 return value.toDouble() / zoomFactor;
655 enum LegacyCSSOMElementMetricsRoundingStrategy { Round, Floor };
657 static bool subpixelMetricsEnabled(const Document& document)
659 return document.settings() && document.settings()->subpixelCSSOMElementMetricsEnabled();
662 static double convertToNonSubpixelValueIfNeeded(double value, const Document& document, LegacyCSSOMElementMetricsRoundingStrategy roundStrategy = Round)
664 return subpixelMetricsEnabled(document) ? value : roundStrategy == Round ? round(value) : floor(value);
667 double Element::offsetLeft()
669 document().updateLayoutIgnorePendingStylesheets();
670 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
671 LayoutUnit offsetLeft = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetLeft() : LayoutUnit(renderer->pixelSnappedOffsetLeft());
672 double zoomFactor = 1;
673 double offsetLeftAdjustedWithZoom = adjustForLocalZoom(offsetLeft, *renderer, zoomFactor);
674 return convertToNonSubpixelValueIfNeeded(offsetLeftAdjustedWithZoom, renderer->document(), zoomFactor == 1 ? Floor : Round);
679 double Element::offsetTop()
681 document().updateLayoutIgnorePendingStylesheets();
682 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
683 LayoutUnit offsetTop = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetTop() : LayoutUnit(renderer->pixelSnappedOffsetTop());
684 double zoomFactor = 1;
685 double offsetTopAdjustedWithZoom = adjustForLocalZoom(offsetTop, *renderer, zoomFactor);
686 return convertToNonSubpixelValueIfNeeded(offsetTopAdjustedWithZoom, renderer->document(), zoomFactor == 1 ? Floor : Round);
691 double Element::offsetWidth()
693 document().updateLayoutIgnorePendingStylesheets();
694 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
695 LayoutUnit offsetWidth = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetWidth() : LayoutUnit(renderer->pixelSnappedOffsetWidth());
696 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(offsetWidth, *renderer).toDouble(), renderer->document());
701 double Element::offsetHeight()
703 document().updateLayoutIgnorePendingStylesheets();
704 if (RenderBoxModelObject* renderer = renderBoxModelObject()) {
705 LayoutUnit offsetHeight = subpixelMetricsEnabled(renderer->document()) ? renderer->offsetHeight() : LayoutUnit(renderer->pixelSnappedOffsetHeight());
706 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(offsetHeight, *renderer).toDouble(), renderer->document());
711 Element* Element::bindingsOffsetParent()
713 Element* element = offsetParent();
714 if (!element || !element->isInShadowTree())
716 return element->containingShadowRoot()->type() == ShadowRoot::UserAgentShadowRoot ? 0 : element;
719 Element* Element::offsetParent()
721 document().updateLayoutIgnorePendingStylesheets();
722 auto renderer = this->renderer();
725 auto offsetParent = renderer->offsetParent();
728 return offsetParent->element();
731 double Element::clientLeft()
733 document().updateLayoutIgnorePendingStylesheets();
735 if (RenderBox* renderer = renderBox()) {
736 LayoutUnit clientLeft = subpixelMetricsEnabled(renderer->document()) ? renderer->clientLeft() : LayoutUnit(roundToInt(renderer->clientLeft()));
737 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientLeft, *renderer).toDouble(), renderer->document());
742 double Element::clientTop()
744 document().updateLayoutIgnorePendingStylesheets();
746 if (RenderBox* renderer = renderBox()) {
747 LayoutUnit clientTop = subpixelMetricsEnabled(renderer->document()) ? renderer->clientTop() : LayoutUnit(roundToInt(renderer->clientTop()));
748 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientTop, *renderer).toDouble(), renderer->document());
753 double Element::clientWidth()
755 document().updateLayoutIgnorePendingStylesheets();
757 if (!document().hasLivingRenderTree())
759 RenderView& renderView = *document().renderView();
761 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
762 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
763 bool inQuirksMode = document().inQuirksMode();
764 if ((!inQuirksMode && document().documentElement() == this) || (inQuirksMode && isHTMLElement() && document().body() == this))
765 return adjustForAbsoluteZoom(renderView.frameView().layoutWidth(), renderView);
767 if (RenderBox* renderer = renderBox()) {
768 LayoutUnit clientWidth = subpixelMetricsEnabled(renderer->document()) ? renderer->clientWidth() : LayoutUnit(renderer->pixelSnappedClientWidth());
769 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientWidth, *renderer).toDouble(), renderer->document());
774 double Element::clientHeight()
776 document().updateLayoutIgnorePendingStylesheets();
778 if (!document().hasLivingRenderTree())
780 RenderView& renderView = *document().renderView();
782 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
783 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
784 bool inQuirksMode = document().inQuirksMode();
785 if ((!inQuirksMode && document().documentElement() == this) || (inQuirksMode && isHTMLElement() && document().body() == this))
786 return adjustForAbsoluteZoom(renderView.frameView().layoutHeight(), renderView);
788 if (RenderBox* renderer = renderBox()) {
789 LayoutUnit clientHeight = subpixelMetricsEnabled(renderer->document()) ? renderer->clientHeight() : LayoutUnit(renderer->pixelSnappedClientHeight());
790 return convertToNonSubpixelValueIfNeeded(adjustLayoutUnitForAbsoluteZoom(clientHeight, *renderer).toDouble(), renderer->document());
795 int Element::scrollLeft()
797 document().updateLayoutIgnorePendingStylesheets();
799 if (RenderBox* rend = renderBox())
800 return adjustForAbsoluteZoom(rend->scrollLeft(), *rend);
804 int Element::scrollTop()
806 document().updateLayoutIgnorePendingStylesheets();
808 if (RenderBox* rend = renderBox())
809 return adjustForAbsoluteZoom(rend->scrollTop(), *rend);
813 void Element::setScrollLeft(int newLeft)
815 document().updateLayoutIgnorePendingStylesheets();
817 if (RenderBox* renderer = renderBox()) {
818 renderer->setScrollLeft(static_cast<int>(newLeft * renderer->style().effectiveZoom()));
819 if (auto* scrollableArea = renderer->layer())
820 scrollableArea->setScrolledProgrammatically(true);
824 void Element::setScrollTop(int newTop)
826 document().updateLayoutIgnorePendingStylesheets();
828 if (RenderBox* renderer = renderBox()) {
829 renderer->setScrollTop(static_cast<int>(newTop * renderer->style().effectiveZoom()));
830 if (auto* scrollableArea = renderer->layer())
831 scrollableArea->setScrolledProgrammatically(true);
835 int Element::scrollWidth()
837 document().updateLayoutIgnorePendingStylesheets();
838 if (RenderBox* rend = renderBox())
839 return adjustForAbsoluteZoom(rend->scrollWidth(), *rend);
843 int Element::scrollHeight()
845 document().updateLayoutIgnorePendingStylesheets();
846 if (RenderBox* rend = renderBox())
847 return adjustForAbsoluteZoom(rend->scrollHeight(), *rend);
851 IntRect Element::boundsInRootViewSpace()
853 document().updateLayoutIgnorePendingStylesheets();
855 FrameView* view = document().view();
859 Vector<FloatQuad> quads;
861 if (isSVGElement() && renderer()) {
862 // Get the bounding rectangle from the SVG model.
863 SVGElement& svgElement = downcast<SVGElement>(*this);
865 if (svgElement.getBoundingBox(localRect))
866 quads.append(renderer()->localToAbsoluteQuad(localRect));
868 // Get the bounding rectangle from the box model.
869 if (renderBoxModelObject())
870 renderBoxModelObject()->absoluteQuads(quads);
876 IntRect result = quads[0].enclosingBoundingBox();
877 for (size_t i = 1; i < quads.size(); ++i)
878 result.unite(quads[i].enclosingBoundingBox());
880 result = view->contentsToRootView(result);
884 PassRefPtr<ClientRectList> Element::getClientRects()
886 document().updateLayoutIgnorePendingStylesheets();
888 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
889 if (!renderBoxModelObject)
890 return ClientRectList::create();
892 // FIXME: Handle SVG elements.
893 // FIXME: Handle table/inline-table with a caption.
895 Vector<FloatQuad> quads;
896 renderBoxModelObject->absoluteQuads(quads);
897 document().adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(quads, renderBoxModelObject->style());
898 return ClientRectList::create(quads);
901 PassRefPtr<ClientRect> Element::getBoundingClientRect()
903 document().updateLayoutIgnorePendingStylesheets();
905 Vector<FloatQuad> quads;
906 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
907 // Get the bounding rectangle from the SVG model.
908 SVGElement& svgElement = downcast<SVGElement>(*this);
910 if (svgElement.getBoundingBox(localRect))
911 quads.append(renderer()->localToAbsoluteQuad(localRect));
913 // Get the bounding rectangle from the box model.
914 if (renderBoxModelObject())
915 renderBoxModelObject()->absoluteQuads(quads);
919 return ClientRect::create();
921 FloatRect result = quads[0].boundingBox();
922 for (size_t i = 1; i < quads.size(); ++i)
923 result.unite(quads[i].boundingBox());
925 document().adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(result, renderer()->style());
926 return ClientRect::create(result);
929 IntRect Element::clientRect() const
931 if (RenderObject* renderer = this->renderer())
932 return document().view()->contentsToRootView(renderer->absoluteBoundingBoxRect());
936 IntRect Element::screenRect() const
938 if (RenderObject* renderer = this->renderer())
939 return document().view()->contentsToScreen(renderer->absoluteBoundingBoxRect());
943 const AtomicString& Element::getAttribute(const AtomicString& localName) const
947 synchronizeAttribute(localName);
948 if (const Attribute* attribute = elementData()->findAttributeByName(localName, shouldIgnoreAttributeCase(*this)))
949 return attribute->value();
953 const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
955 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
958 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionCode& ec)
960 if (!Document::isValidName(localName)) {
961 ec = INVALID_CHARACTER_ERR;
965 synchronizeAttribute(localName);
966 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(*this) ? localName.lower() : localName;
968 unsigned index = elementData() ? elementData()->findAttributeIndexByName(caseAdjustedLocalName, false) : ElementData::attributeNotFound;
969 const QualifiedName& qName = index != ElementData::attributeNotFound ? attributeAt(index).name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
970 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
973 void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
975 synchronizeAttribute(name);
976 unsigned index = elementData() ? elementData()->findAttributeIndexByName(name) : ElementData::attributeNotFound;
977 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
980 void Element::setAttributeWithoutSynchronization(const QualifiedName& name, const AtomicString& value)
982 unsigned index = elementData() ? elementData()->findAttributeIndexByName(name) : ElementData::attributeNotFound;
983 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
986 void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
988 unsigned index = elementData() ? elementData()->findAttributeIndexByName(name) : ElementData::attributeNotFound;
989 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
992 inline void Element::setAttributeInternal(unsigned index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
994 if (newValue.isNull()) {
995 if (index != ElementData::attributeNotFound)
996 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
1000 if (index == ElementData::attributeNotFound) {
1001 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
1005 const Attribute& attribute = attributeAt(index);
1006 AtomicString oldValue = attribute.value();
1007 bool valueChanged = newValue != oldValue;
1008 QualifiedName attributeName = (!inSynchronizationOfLazyAttribute || valueChanged) ? attribute.name() : name;
1010 if (!inSynchronizationOfLazyAttribute)
1011 willModifyAttribute(attributeName, oldValue, newValue);
1014 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
1015 // will write into the ElementData.
1016 // FIXME: Refactor this so it makes some sense.
1017 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(attributeName))
1018 attrNode->setValue(newValue);
1020 ensureUniqueElementData().attributeAt(index).setValue(newValue);
1023 if (!inSynchronizationOfLazyAttribute)
1024 didModifyAttribute(attributeName, oldValue, newValue);
1027 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
1030 return value.lower();
1034 static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, StyleResolver* styleResolver)
1036 ASSERT(newId != oldId);
1037 if (!oldId.isEmpty() && styleResolver->hasSelectorForId(oldId))
1039 if (!newId.isEmpty() && styleResolver->hasSelectorForId(newId))
1044 void Element::attributeChanged(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue, AttributeModificationReason)
1046 parseAttribute(name, newValue);
1048 document().incDOMTreeVersion();
1050 if (oldValue == newValue)
1053 StyleResolver* styleResolver = document().styleResolverIfExists();
1054 bool testShouldInvalidateStyle = inRenderedDocument() && styleResolver && styleChangeType() < FullStyleChange;
1055 bool shouldInvalidateStyle = false;
1057 if (name == HTMLNames::idAttr) {
1058 AtomicString oldId = elementData()->idForStyleResolution();
1059 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1060 if (newId != oldId) {
1061 elementData()->setIdForStyleResolution(newId);
1062 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver);
1064 } else if (name == classAttr)
1065 classAttributeChanged(newValue);
1066 else if (name == HTMLNames::nameAttr)
1067 elementData()->setHasNameAttribute(!newValue.isNull());
1068 else if (name == HTMLNames::pseudoAttr)
1069 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
1072 invalidateNodeListAndCollectionCachesInAncestors(&name, this);
1074 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
1075 shouldInvalidateStyle |= !styleResolver;
1077 if (shouldInvalidateStyle)
1078 setNeedsStyleRecalc();
1080 if (AXObjectCache* cache = document().existingAXObjectCache())
1081 cache->handleAttributeChanged(name, this);
1084 template <typename CharacterType>
1085 static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
1091 if (isNotHTMLSpace(characters[i]))
1094 } while (i < length);
1099 static inline bool classStringHasClassName(const AtomicString& newClassString)
1101 unsigned length = newClassString.length();
1106 if (newClassString.is8Bit())
1107 return classStringHasClassName(newClassString.characters8(), length);
1108 return classStringHasClassName(newClassString.characters16(), length);
1111 static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const StyleResolver& styleResolver)
1113 unsigned changedSize = changedClasses.size();
1114 for (unsigned i = 0; i < changedSize; ++i) {
1115 if (styleResolver.hasSelectorForClass(changedClasses[i]))
1121 static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const StyleResolver& styleResolver)
1123 unsigned oldSize = oldClasses.size();
1125 return checkSelectorForClassChange(newClasses, styleResolver);
1126 BitVector remainingClassBits;
1127 remainingClassBits.ensureSize(oldSize);
1128 // Class vectors tend to be very short. This is faster than using a hash table.
1129 unsigned newSize = newClasses.size();
1130 for (unsigned i = 0; i < newSize; ++i) {
1131 bool foundFromBoth = false;
1132 for (unsigned j = 0; j < oldSize; ++j) {
1133 if (newClasses[i] == oldClasses[j]) {
1134 remainingClassBits.quickSet(j);
1135 foundFromBoth = true;
1140 if (styleResolver.hasSelectorForClass(newClasses[i]))
1143 for (unsigned i = 0; i < oldSize; ++i) {
1144 // If the bit is not set the the corresponding class has been removed.
1145 if (remainingClassBits.quickGet(i))
1147 if (styleResolver.hasSelectorForClass(oldClasses[i]))
1153 void Element::classAttributeChanged(const AtomicString& newClassString)
1155 StyleResolver* styleResolver = document().styleResolverIfExists();
1156 bool testShouldInvalidateStyle = inRenderedDocument() && styleResolver && styleChangeType() < FullStyleChange;
1157 bool shouldInvalidateStyle = false;
1159 if (classStringHasClassName(newClassString)) {
1160 const bool shouldFoldCase = document().inQuirksMode();
1161 // Note: We'll need ElementData, but it doesn't have to be UniqueElementData.
1163 ensureUniqueElementData();
1164 const SpaceSplitString oldClasses = elementData()->classNames();
1165 elementData()->setClass(newClassString, shouldFoldCase);
1166 const SpaceSplitString& newClasses = elementData()->classNames();
1167 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver);
1168 } else if (elementData()) {
1169 const SpaceSplitString& oldClasses = elementData()->classNames();
1170 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver);
1171 elementData()->clearClass();
1175 elementRareData()->clearClassListValueForQuirksMode();
1177 if (shouldInvalidateStyle)
1178 setNeedsStyleRecalc();
1181 URL Element::absoluteLinkURL() const
1186 AtomicString linkAttribute;
1187 if (hasTagName(SVGNames::aTag))
1188 linkAttribute = getAttribute(XLinkNames::hrefAttr);
1190 linkAttribute = getAttribute(HTMLNames::hrefAttr);
1192 if (linkAttribute.isEmpty())
1195 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(linkAttribute));
1198 // Returns true is the given attribute is an event handler.
1199 // We consider an event handler any attribute that begins with "on".
1200 // It is a simple solution that has the advantage of not requiring any
1201 // code or configuration change if a new event handler is defined.
1203 static inline bool isEventHandlerAttribute(const Attribute& attribute)
1205 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1208 bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1210 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1213 void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1215 size_t destination = 0;
1216 for (size_t source = 0; source < attributeVector.size(); ++source) {
1217 if (isEventHandlerAttribute(attributeVector[source])
1218 || isJavaScriptURLAttribute(attributeVector[source])
1219 || isHTMLContentAttribute(attributeVector[source]))
1222 if (source != destination)
1223 attributeVector[destination] = attributeVector[source];
1227 attributeVector.shrink(destination);
1230 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1232 ASSERT(!inDocument());
1233 ASSERT(!parentNode());
1234 ASSERT(!m_elementData);
1236 if (attributeVector.isEmpty())
1239 if (document().sharedObjectPool())
1240 m_elementData = document().sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
1242 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1244 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1245 for (unsigned i = 0; i < attributeVector.size(); ++i)
1246 attributeChanged(attributeVector[i].name(), nullAtom, attributeVector[i].value(), ModifiedDirectly);
1249 bool Element::hasAttributes() const
1251 synchronizeAllAttributes();
1252 return elementData() && elementData()->length();
1255 bool Element::hasEquivalentAttributes(const Element* other) const
1257 synchronizeAllAttributes();
1258 other->synchronizeAllAttributes();
1259 if (elementData() == other->elementData())
1262 return elementData()->isEquivalent(other->elementData());
1263 if (other->elementData())
1264 return other->elementData()->isEquivalent(elementData());
1268 String Element::nodeName() const
1270 return m_tagName.toString();
1273 String Element::nodeNamePreservingCase() const
1275 return m_tagName.toString();
1278 void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec)
1281 checkSetPrefix(prefix, ec);
1285 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1288 URL Element::baseURI() const
1290 const AtomicString& baseAttribute = getAttribute(baseAttr);
1291 URL base(URL(), baseAttribute);
1292 if (!base.protocol().isEmpty())
1295 ContainerNode* parent = parentNode();
1299 const URL& parentBase = parent->baseURI();
1300 if (parentBase.isNull())
1303 return URL(parentBase, baseAttribute);
1306 const AtomicString& Element::imageSourceURL() const
1308 return fastGetAttribute(srcAttr);
1311 bool Element::rendererIsNeeded(const RenderStyle& style)
1313 return style.display() != NONE;
1316 RenderPtr<RenderElement> Element::createElementRenderer(PassRef<RenderStyle> style)
1318 return RenderElement::createFor(*this, WTF::move(style));
1321 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode& insertionPoint)
1323 bool wasInDocument = inDocument();
1324 // need to do superclass processing first so inDocument() is true
1325 // by the time we reach updateId
1326 ContainerNode::insertedInto(insertionPoint);
1327 ASSERT(!wasInDocument || inDocument());
1329 #if ENABLE(FULLSCREEN_API)
1330 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1331 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1334 if (!insertionPoint.isInTreeScope())
1335 return InsertionDone;
1338 elementRareData()->clearClassListValueForQuirksMode();
1340 TreeScope* newScope = &insertionPoint.treeScope();
1341 HTMLDocument* newDocument = !wasInDocument && inDocument() && newScope->documentScope().isHTMLDocument() ? toHTMLDocument(&newScope->documentScope()) : nullptr;
1342 if (newScope != &treeScope())
1345 const AtomicString& idValue = getIdAttribute();
1346 if (!idValue.isNull()) {
1348 updateIdForTreeScope(*newScope, nullAtom, idValue);
1350 updateIdForDocument(*newDocument, nullAtom, idValue, AlwaysUpdateHTMLDocumentNamedItemMaps);
1353 const AtomicString& nameValue = getNameAttribute();
1354 if (!nameValue.isNull()) {
1356 updateNameForTreeScope(*newScope, nullAtom, nameValue);
1358 updateNameForDocument(*newDocument, nullAtom, nameValue);
1361 if (newScope && hasTagName(labelTag)) {
1362 if (newScope->shouldCacheLabelsByForAttribute())
1363 updateLabel(*newScope, nullAtom, fastGetAttribute(forAttr));
1366 return InsertionDone;
1369 void Element::removedFrom(ContainerNode& insertionPoint)
1371 #if ENABLE(FULLSCREEN_API)
1372 if (containsFullScreenElement())
1373 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1375 #if ENABLE(POINTER_LOCK)
1376 if (document().page())
1377 document().page()->pointerLockController().elementRemoved(this);
1380 setSavedLayerScrollOffset(IntSize());
1382 if (insertionPoint.isInTreeScope()) {
1383 TreeScope* oldScope = &insertionPoint.treeScope();
1384 HTMLDocument* oldDocument = inDocument() && oldScope->documentScope().isHTMLDocument() ? toHTMLDocument(&oldScope->documentScope()) : nullptr;
1385 if (oldScope != &treeScope() || !isInTreeScope())
1388 const AtomicString& idValue = getIdAttribute();
1389 if (!idValue.isNull()) {
1391 updateIdForTreeScope(*oldScope, idValue, nullAtom);
1393 updateIdForDocument(*oldDocument, idValue, nullAtom, AlwaysUpdateHTMLDocumentNamedItemMaps);
1396 const AtomicString& nameValue = getNameAttribute();
1397 if (!nameValue.isNull()) {
1399 updateNameForTreeScope(*oldScope, nameValue, nullAtom);
1401 updateNameForDocument(*oldDocument, nameValue, nullAtom);
1404 if (oldScope && hasTagName(labelTag)) {
1405 if (oldScope->shouldCacheLabelsByForAttribute())
1406 updateLabel(*oldScope, fastGetAttribute(forAttr), nullAtom);
1410 ContainerNode::removedFrom(insertionPoint);
1412 if (hasPendingResources())
1413 document().accessSVGExtensions().removeElementFromPendingResources(this);
1416 void Element::unregisterNamedFlowContentElement()
1418 if (document().cssRegionsEnabled() && isNamedFlowContentNode() && document().renderView())
1419 document().renderView()->flowThreadController().unregisterNamedFlowContentElement(*this);
1422 ShadowRoot* Element::shadowRoot() const
1424 return hasRareData() ? elementRareData()->shadowRoot() : 0;
1427 void Element::didAffectSelector(AffectedSelectorMask)
1429 setNeedsStyleRecalc();
1432 static bool shouldUseNodeRenderingTraversalSlowPath(const Element& element)
1434 if (element.isShadowRoot())
1436 return element.isInsertionPoint() || element.shadowRoot();
1439 void Element::resetNeedsNodeRenderingTraversalSlowPath()
1441 setNeedsNodeRenderingTraversalSlowPath(shouldUseNodeRenderingTraversalSlowPath(*this));
1444 void Element::addShadowRoot(PassRefPtr<ShadowRoot> newShadowRoot)
1446 ASSERT(!shadowRoot());
1448 ShadowRoot* shadowRoot = newShadowRoot.get();
1449 ensureElementRareData().setShadowRoot(newShadowRoot);
1451 shadowRoot->setHostElement(this);
1452 shadowRoot->setParentTreeScope(&treeScope());
1453 shadowRoot->distributor().didShadowBoundaryChange(this);
1455 ChildNodeInsertionNotifier(*this).notify(*shadowRoot);
1457 resetNeedsNodeRenderingTraversalSlowPath();
1459 setNeedsStyleRecalc(ReconstructRenderTree);
1461 InspectorInstrumentation::didPushShadowRoot(this, shadowRoot);
1464 void Element::removeShadowRoot()
1466 RefPtr<ShadowRoot> oldRoot = shadowRoot();
1469 InspectorInstrumentation::willPopShadowRoot(this, oldRoot.get());
1470 document().removeFocusedNodeOfSubtree(oldRoot.get());
1472 ASSERT(!oldRoot->renderer());
1474 elementRareData()->clearShadowRoot();
1476 oldRoot->setHostElement(0);
1477 oldRoot->setParentTreeScope(&document());
1479 ChildNodeRemovalNotifier(*this).notify(*oldRoot);
1481 oldRoot->distributor().invalidateDistribution(this);
1484 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1486 if (alwaysCreateUserAgentShadowRoot())
1487 ensureUserAgentShadowRoot();
1489 ec = HIERARCHY_REQUEST_ERR;
1493 ShadowRoot* Element::userAgentShadowRoot() const
1495 if (ShadowRoot* shadowRoot = this->shadowRoot()) {
1496 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1502 ShadowRoot& Element::ensureUserAgentShadowRoot()
1504 ShadowRoot* shadowRoot = userAgentShadowRoot();
1506 addShadowRoot(ShadowRoot::create(document(), ShadowRoot::UserAgentShadowRoot));
1507 shadowRoot = userAgentShadowRoot();
1508 didAddUserAgentShadowRoot(shadowRoot);
1513 const AtomicString& Element::shadowPseudoId() const
1518 bool Element::childTypeAllowed(NodeType type) const
1524 case PROCESSING_INSTRUCTION_NODE:
1525 case CDATA_SECTION_NODE:
1526 case ENTITY_REFERENCE_NODE:
1534 static void checkForEmptyStyleChange(Element& element)
1536 if (element.styleAffectedByEmpty()) {
1537 RenderStyle* style = element.renderStyle();
1538 if (!style || (!style->emptyState() || element.hasChildNodes()))
1539 element.setNeedsStyleRecalc();
1543 enum SiblingCheckType { FinishedParsingChildren, SiblingElementRemoved, Other };
1545 static void checkForSiblingStyleChanges(Element* parent, SiblingCheckType checkType, Element* elementBeforeChange, Element* elementAfterChange)
1548 checkForEmptyStyleChange(*parent);
1550 if (parent->styleChangeType() >= FullStyleChange)
1553 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1554 // In the DOM case, we only need to do something if |afterChange| is not 0.
1555 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1556 if (parent->childrenAffectedByFirstChildRules() && elementAfterChange) {
1557 // Find our new first child.
1558 Element* newFirstElement = ElementTraversal::firstChild(parent);
1559 // Find the first element node following |afterChange|
1561 // This is the insert/append case.
1562 if (newFirstElement != elementAfterChange) {
1563 RenderStyle* style = elementAfterChange->renderStyle();
1564 if (!style || style->firstChildState())
1565 elementAfterChange->setNeedsStyleRecalc();
1568 // We also have to handle node removal.
1569 if (checkType == SiblingElementRemoved && newFirstElement == elementAfterChange && newFirstElement) {
1570 RenderStyle* style = newFirstElement->renderStyle();
1571 if (!style || !style->firstChildState())
1572 newFirstElement->setNeedsStyleRecalc();
1576 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1577 // In the DOM case, we only need to do something if |afterChange| is not 0.
1578 if (parent->childrenAffectedByLastChildRules() && elementBeforeChange) {
1579 // Find our new last child.
1580 Element* newLastElement = ElementTraversal::lastChild(parent);
1582 if (newLastElement != elementBeforeChange) {
1583 RenderStyle* style = elementBeforeChange->renderStyle();
1584 if (!style || style->lastChildState())
1585 elementBeforeChange->setNeedsStyleRecalc();
1588 // 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
1590 if ((checkType == SiblingElementRemoved || checkType == FinishedParsingChildren) && newLastElement == elementBeforeChange && newLastElement) {
1591 RenderStyle* style = newLastElement->renderStyle();
1592 if (!style || !style->lastChildState())
1593 newLastElement->setNeedsStyleRecalc();
1597 if (elementAfterChange) {
1598 if (elementAfterChange->styleIsAffectedByPreviousSibling())
1599 elementAfterChange->setNeedsStyleRecalc();
1600 else if (elementAfterChange->affectsNextSiblingElementStyle()) {
1601 Element* elementToInvalidate = elementAfterChange;
1603 elementToInvalidate = elementToInvalidate->nextElementSibling();
1604 } while (elementToInvalidate && !elementToInvalidate->styleIsAffectedByPreviousSibling());
1606 if (elementToInvalidate)
1607 elementToInvalidate->setNeedsStyleRecalc();
1611 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1612 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1614 // |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.
1615 // 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
1616 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1617 if (parent->childrenAffectedByBackwardPositionalRules() && elementBeforeChange)
1618 parent->setNeedsStyleRecalc();
1621 void Element::childrenChanged(const ChildChange& change)
1623 ContainerNode::childrenChanged(change);
1624 if (change.source == ChildChangeSourceParser)
1625 checkForEmptyStyleChange(*this);
1627 SiblingCheckType checkType = change.type == ElementRemoved ? SiblingElementRemoved : Other;
1628 checkForSiblingStyleChanges(this, checkType, change.previousSiblingElement, change.nextSiblingElement);
1631 if (ShadowRoot* shadowRoot = this->shadowRoot())
1632 shadowRoot->invalidateDistribution();
1635 void Element::removeAllEventListeners()
1637 ContainerNode::removeAllEventListeners();
1638 if (ShadowRoot* shadowRoot = this->shadowRoot())
1639 shadowRoot->removeAllEventListeners();
1642 void Element::beginParsingChildren()
1644 clearIsParsingChildrenFinished();
1645 if (auto styleResolver = document().styleResolverIfExists())
1646 styleResolver->pushParentElement(this);
1649 void Element::finishParsingChildren()
1651 ContainerNode::finishParsingChildren();
1652 setIsParsingChildrenFinished();
1653 checkForSiblingStyleChanges(this, FinishedParsingChildren, ElementTraversal::lastChild(this), nullptr);
1654 if (auto styleResolver = document().styleResolverIfExists())
1655 styleResolver->popParentElement(this);
1659 void Element::formatForDebugger(char* buffer, unsigned length) const
1661 StringBuilder result;
1664 result.append(nodeName());
1666 s = getIdAttribute();
1667 if (s.length() > 0) {
1668 if (result.length() > 0)
1669 result.appendLiteral("; ");
1670 result.appendLiteral("id=");
1674 s = getAttribute(classAttr);
1675 if (s.length() > 0) {
1676 if (result.length() > 0)
1677 result.appendLiteral("; ");
1678 result.appendLiteral("class=");
1682 strncpy(buffer, result.toString().utf8().data(), length - 1);
1686 const Vector<RefPtr<Attr>>& Element::attrNodeList()
1688 ASSERT(hasSyntheticAttrChildNodes());
1689 return *attrNodeListForElement(*this);
1692 PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1695 ec = TYPE_MISMATCH_ERR;
1699 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1700 if (oldAttrNode.get() == attrNode)
1701 return attrNode; // This Attr is already attached to the element.
1703 // INUSE_ATTRIBUTE_ERR: Raised if node is an Attr that is already an attribute of another Element object.
1704 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1705 if (attrNode->ownerElement()) {
1706 ec = INUSE_ATTRIBUTE_ERR;
1710 synchronizeAllAttributes();
1711 UniqueElementData& elementData = ensureUniqueElementData();
1713 unsigned index = elementData.findAttributeIndexByNameForAttributeNode(attrNode, shouldIgnoreAttributeCase(*this));
1714 if (index != ElementData::attributeNotFound) {
1716 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData.attributeAt(index).value());
1718 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData.attributeAt(index).value());
1721 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1723 attrNode->attachToElement(this);
1724 treeScope().adoptIfNeeded(attrNode);
1725 ensureAttrNodeListForElement(*this).append(attrNode);
1727 return oldAttrNode.release();
1730 PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionCode& ec)
1732 return setAttributeNode(attr, ec);
1735 PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1738 ec = TYPE_MISMATCH_ERR;
1741 if (attr->ownerElement() != this) {
1746 ASSERT(&document() == &attr->document());
1748 synchronizeAttribute(attr->qualifiedName());
1750 unsigned index = elementData()->findAttributeIndexByNameForAttributeNode(attr);
1751 if (index == ElementData::attributeNotFound) {
1756 RefPtr<Attr> attrNode = attr;
1757 detachAttrNodeFromElementWithValue(attr, elementData()->attributeAt(index).value());
1758 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1759 return attrNode.release();
1762 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1764 String prefix, localName;
1765 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1769 QualifiedName qName(prefix, localName, namespaceURI);
1771 if (!Document::hasValidNamespaceForAttributes(qName)) {
1780 void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1782 QualifiedName parsedName = anyName;
1783 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1785 setAttribute(parsedName, value);
1788 void Element::removeAttributeInternal(unsigned index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1790 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1792 UniqueElementData& elementData = ensureUniqueElementData();
1794 QualifiedName name = elementData.attributeAt(index).name();
1795 AtomicString valueBeingRemoved = elementData.attributeAt(index).value();
1797 if (!inSynchronizationOfLazyAttribute) {
1798 if (!valueBeingRemoved.isNull())
1799 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1802 if (RefPtr<Attr> attrNode = attrIfExists(name))
1803 detachAttrNodeFromElementWithValue(attrNode.get(), elementData.attributeAt(index).value());
1805 elementData.removeAttribute(index);
1807 if (!inSynchronizationOfLazyAttribute)
1808 didRemoveAttribute(name, valueBeingRemoved);
1811 void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1813 if (!inSynchronizationOfLazyAttribute)
1814 willModifyAttribute(name, nullAtom, value);
1815 ensureUniqueElementData().addAttribute(name, value);
1816 if (!inSynchronizationOfLazyAttribute)
1817 didAddAttribute(name, value);
1820 bool Element::removeAttribute(const AtomicString& name)
1825 AtomicString localName = shouldIgnoreAttributeCase(*this) ? name.lower() : name;
1826 unsigned index = elementData()->findAttributeIndexByName(localName, false);
1827 if (index == ElementData::attributeNotFound) {
1828 if (UNLIKELY(localName == styleAttr) && elementData()->styleAttributeIsDirty() && isStyledElement())
1829 toStyledElement(this)->removeAllInlineStyleProperties();
1833 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1837 bool Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1839 return removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1842 PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1846 synchronizeAttribute(localName);
1847 const Attribute* attribute = elementData()->findAttributeByName(localName, shouldIgnoreAttributeCase(*this));
1850 return ensureAttr(attribute->name());
1853 PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1857 QualifiedName qName(nullAtom, localName, namespaceURI);
1858 synchronizeAttribute(qName);
1859 const Attribute* attribute = elementData()->findAttributeByName(qName);
1862 return ensureAttr(attribute->name());
1865 bool Element::hasAttribute(const AtomicString& localName) const
1869 synchronizeAttribute(localName);
1870 return elementData()->findAttributeByName(shouldIgnoreAttributeCase(*this) ? localName.lower() : localName, false);
1873 bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1877 QualifiedName qName(nullAtom, localName, namespaceURI);
1878 synchronizeAttribute(qName);
1879 return elementData()->findAttributeByName(qName);
1882 CSSStyleDeclaration *Element::style()
1887 void Element::focus(bool restorePreviousSelection, FocusDirection direction)
1892 if (document().focusedElement() == this)
1895 // If the stylesheets have already been loaded we can reliably check isFocusable.
1896 // If not, we continue and set the focused node on the focus controller below so
1897 // that it can be updated soon after attach.
1898 if (document().haveStylesheetsLoaded()) {
1899 document().updateLayoutIgnorePendingStylesheets();
1904 if (!supportsFocus())
1907 RefPtr<Node> protect;
1908 if (Page* page = document().page()) {
1909 // Focus and change event handlers can cause us to lose our last ref.
1910 // If a focus event handler changes the focus to a different node it
1911 // does not make sense to continue and update appearence.
1913 if (!page->focusController().setFocusedElement(this, document().frame(), direction))
1917 // Setting the focused node above might have invalidated the layout due to scripts.
1918 document().updateLayoutIgnorePendingStylesheets();
1920 if (!isFocusable()) {
1921 ensureElementRareData().setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
1925 cancelFocusAppearanceUpdate();
1927 // Focusing a form element triggers animation in UIKit to scroll to the right position.
1928 // Calling updateFocusAppearance() would generate an unnecessary call to ScrollView::setScrollPosition(),
1929 // which would jump us around during this animation. See <rdar://problem/6699741>.
1930 FrameView* view = document().view();
1931 bool isFormControl = view && isFormControlElement();
1933 view->setProhibitsScrolling(true);
1935 updateFocusAppearance(restorePreviousSelection);
1938 view->setProhibitsScrolling(false);
1942 void Element::updateFocusAppearanceAfterAttachIfNeeded()
1946 ElementRareData* data = elementRareData();
1947 if (!data->needsFocusAppearanceUpdateSoonAfterAttach())
1949 if (isFocusable() && document().focusedElement() == this)
1950 document().updateFocusAppearanceSoon(false /* don't restore selection */);
1951 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1954 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
1956 if (isRootEditableElement()) {
1957 Frame* frame = document().frame();
1961 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
1962 if (this == frame->selection().selection().rootEditableElement())
1965 // FIXME: We should restore the previous selection if there is one.
1966 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
1968 if (frame->selection().shouldChangeSelection(newSelection)) {
1969 frame->selection().setSelection(newSelection);
1970 frame->selection().revealSelection();
1972 } else if (renderer() && !renderer()->isWidget())
1973 renderer()->scrollRectToVisible(boundingBox());
1976 void Element::blur()
1978 cancelFocusAppearanceUpdate();
1979 if (treeScope().focusedElement() == this) {
1980 if (Frame* frame = document().frame())
1981 frame->page()->focusController().setFocusedElement(0, frame);
1983 document().setFocusedElement(0);
1987 void Element::dispatchFocusInEvent(const AtomicString& eventType, PassRefPtr<Element> oldFocusedElement)
1989 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
1990 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
1991 dispatchScopedEvent(FocusEvent::create(eventType, true, false, document().defaultView(), 0, oldFocusedElement));
1994 void Element::dispatchFocusOutEvent(const AtomicString& eventType, PassRefPtr<Element> newFocusedElement)
1996 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
1997 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
1998 dispatchScopedEvent(FocusEvent::create(eventType, true, false, document().defaultView(), 0, newFocusedElement));
2001 void Element::dispatchFocusEvent(PassRefPtr<Element> oldFocusedElement, FocusDirection)
2003 if (document().page())
2004 document().page()->chrome().client().elementDidFocus(this);
2006 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document().defaultView(), 0, oldFocusedElement);
2007 EventDispatcher::dispatchEvent(this, event.release());
2010 void Element::dispatchBlurEvent(PassRefPtr<Element> newFocusedElement)
2012 if (document().page())
2013 document().page()->chrome().client().elementDidBlur(this);
2015 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document().defaultView(), 0, newFocusedElement);
2016 EventDispatcher::dispatchEvent(this, event.release());
2020 String Element::innerText()
2022 // We need to update layout, since plainText uses line boxes in the render tree.
2023 document().updateLayoutIgnorePendingStylesheets();
2026 return textContent(true);
2028 return plainText(rangeOfContents(*this).get());
2031 String Element::outerText()
2033 // Getting outerText is the same as getting innerText, only
2034 // setting is different. You would think this should get the plain
2035 // text for the outer range, but this is wrong, <br> for instance
2036 // would return different values for inner and outer text by such
2037 // a rule, but it doesn't in WinIE, and we want to match that.
2041 String Element::title() const
2046 const AtomicString& Element::pseudo() const
2048 return fastGetAttribute(pseudoAttr);
2051 void Element::setPseudo(const AtomicString& value)
2053 setAttributeWithoutSynchronization(pseudoAttr, value);
2056 LayoutSize Element::minimumSizeForResizing() const
2058 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2061 void Element::setMinimumSizeForResizing(const LayoutSize& size)
2063 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2065 ensureElementRareData().setMinimumSizeForResizing(size);
2068 static PseudoElement* beforeOrAfterPseudoElement(Element* host, PseudoId pseudoElementSpecifier)
2070 switch (pseudoElementSpecifier) {
2072 return host->beforePseudoElement();
2074 return host->afterPseudoElement();
2080 RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2082 if (PseudoElement* pseudoElement = beforeOrAfterPseudoElement(this, pseudoElementSpecifier))
2083 return pseudoElement->computedStyle();
2085 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2086 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2087 // values returned for the ":selection" pseudo-element will be correct.
2088 if (RenderStyle* usedStyle = renderStyle()) {
2089 if (pseudoElementSpecifier) {
2090 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2091 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2096 if (!inDocument()) {
2097 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2098 // document tree and figure out when to destroy the computed style for such elements.
2102 ElementRareData& data = ensureElementRareData();
2103 if (!data.computedStyle())
2104 data.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
2105 return pseudoElementSpecifier ? data.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data.computedStyle();
2108 void Element::setStyleAffectedByEmpty()
2110 ensureElementRareData().setStyleAffectedByEmpty(true);
2113 void Element::setChildrenAffectedByActive()
2115 ensureElementRareData().setChildrenAffectedByActive(true);
2118 void Element::setChildrenAffectedByDrag()
2120 ensureElementRareData().setChildrenAffectedByDrag(true);
2123 void Element::setChildrenAffectedByBackwardPositionalRules()
2125 ensureElementRareData().setChildrenAffectedByBackwardPositionalRules(true);
2128 void Element::setChildIndex(unsigned index)
2130 ElementRareData& rareData = ensureElementRareData();
2131 if (RenderStyle* style = renderStyle())
2133 rareData.setChildIndex(index);
2136 bool Element::hasFlagsSetDuringStylingOfChildren() const
2138 if (childrenAffectedByHover() || childrenAffectedByFirstChildRules() || childrenAffectedByLastChildRules())
2143 return rareDataChildrenAffectedByActive()
2144 || rareDataChildrenAffectedByDrag()
2145 || rareDataChildrenAffectedByBackwardPositionalRules();
2148 bool Element::rareDataStyleAffectedByEmpty() const
2150 ASSERT(hasRareData());
2151 return elementRareData()->styleAffectedByEmpty();
2154 bool Element::rareDataChildrenAffectedByActive() const
2156 ASSERT(hasRareData());
2157 return elementRareData()->childrenAffectedByActive();
2160 bool Element::rareDataChildrenAffectedByDrag() const
2162 ASSERT(hasRareData());
2163 return elementRareData()->childrenAffectedByDrag();
2166 bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2168 ASSERT(hasRareData());
2169 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2172 unsigned Element::rareDataChildIndex() const
2174 ASSERT(hasRareData());
2175 return elementRareData()->childIndex();
2178 void Element::setRegionOversetState(RegionOversetState state)
2180 ensureElementRareData().setRegionOversetState(state);
2183 RegionOversetState Element::regionOversetState() const
2185 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2188 AtomicString Element::computeInheritedLanguage() const
2190 if (const ElementData* elementData = this->elementData()) {
2191 if (const Attribute* attribute = elementData->findLanguageAttribute())
2192 return attribute->value();
2195 // The language property is inherited, so we iterate over the parents to find the first language.
2196 const Node* currentNode = this;
2197 while ((currentNode = currentNode->parentNode())) {
2198 if (currentNode->isElementNode()) {
2199 if (const ElementData* elementData = toElement(*currentNode).elementData()) {
2200 if (const Attribute* attribute = elementData->findLanguageAttribute())
2201 return attribute->value();
2203 } else if (currentNode->isDocumentNode()) {
2204 // checking the MIME content-language
2205 return toDocument(currentNode)->contentLanguage();
2212 Locale& Element::locale() const
2214 return document().getCachedLocale(computeInheritedLanguage());
2217 void Element::cancelFocusAppearanceUpdate()
2220 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2221 if (document().focusedElement() == this)
2222 document().cancelFocusAppearanceUpdate();
2225 void Element::normalizeAttributes()
2227 if (!hasAttributes())
2229 for (const Attribute& attribute : attributesIterator()) {
2230 if (RefPtr<Attr> attr = attrIfExists(attribute.name()))
2235 PseudoElement* Element::beforePseudoElement() const
2237 return hasRareData() ? elementRareData()->beforePseudoElement() : 0;
2240 PseudoElement* Element::afterPseudoElement() const
2242 return hasRareData() ? elementRareData()->afterPseudoElement() : 0;
2245 void Element::setBeforePseudoElement(PassRefPtr<PseudoElement> element)
2247 ensureElementRareData().setBeforePseudoElement(element);
2250 void Element::setAfterPseudoElement(PassRefPtr<PseudoElement> element)
2252 ensureElementRareData().setAfterPseudoElement(element);
2255 static void disconnectPseudoElement(PseudoElement* pseudoElement)
2259 if (pseudoElement->renderer())
2260 Style::detachRenderTree(*pseudoElement);
2261 ASSERT(pseudoElement->hostElement());
2262 pseudoElement->clearHostElement();
2265 void Element::clearBeforePseudoElement()
2269 disconnectPseudoElement(elementRareData()->beforePseudoElement());
2270 elementRareData()->setBeforePseudoElement(nullptr);
2273 void Element::clearAfterPseudoElement()
2277 disconnectPseudoElement(elementRareData()->afterPseudoElement());
2278 elementRareData()->setAfterPseudoElement(nullptr);
2281 // ElementTraversal API
2282 Element* Element::firstElementChild() const
2284 return ElementTraversal::firstChild(this);
2287 Element* Element::lastElementChild() const
2289 return ElementTraversal::lastChild(this);
2292 Element* Element::previousElementSibling() const
2294 return ElementTraversal::previousSibling(this);
2297 Element* Element::nextElementSibling() const
2299 return ElementTraversal::nextSibling(this);
2302 unsigned Element::childElementCount() const
2305 Node* n = firstChild();
2307 count += n->isElementNode();
2308 n = n->nextSibling();
2313 bool Element::matchesReadWritePseudoClass() const
2318 bool Element::matches(const String& selector, ExceptionCode& ec)
2320 SelectorQuery* selectorQuery = document().selectorQueryForString(selector, ec);
2321 return selectorQuery && selectorQuery->matches(*this);
2324 bool Element::shouldAppearIndeterminate() const
2329 DOMTokenList& Element::classList()
2331 ElementRareData& data = ensureElementRareData();
2332 if (!data.classList())
2333 data.setClassList(std::make_unique<ClassList>(*this));
2334 return *data.classList();
2337 DatasetDOMStringMap& Element::dataset()
2339 ElementRareData& data = ensureElementRareData();
2340 if (!data.dataset())
2341 data.setDataset(std::make_unique<DatasetDOMStringMap>(*this));
2342 return *data.dataset();
2345 URL Element::getURLAttribute(const QualifiedName& name) const
2347 #if !ASSERT_DISABLED
2348 if (elementData()) {
2349 if (const Attribute* attribute = findAttributeByName(name))
2350 ASSERT(isURLAttribute(*attribute));
2353 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2356 URL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2358 #if !ASSERT_DISABLED
2359 if (elementData()) {
2360 if (const Attribute* attribute = findAttributeByName(name))
2361 ASSERT(isURLAttribute(*attribute));
2364 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2365 if (value.isEmpty())
2367 return document().completeURL(value);
2370 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2372 return getAttribute(attributeName).string().toInt();
2375 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2377 setAttribute(attributeName, AtomicString::number(value));
2380 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2382 return getAttribute(attributeName).string().toUInt();
2385 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2387 setAttribute(attributeName, AtomicString::number(value));
2390 #if ENABLE(INDIE_UI)
2391 void Element::setUIActions(const AtomicString& actions)
2393 setAttribute(uiactionsAttr, actions);
2396 const AtomicString& Element::UIActions() const
2398 return getAttribute(uiactionsAttr);
2402 bool Element::childShouldCreateRenderer(const Node& child) const
2404 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2405 if (child.isSVGElement()) {
2406 ASSERT(!isSVGElement());
2407 const SVGElement& childElement = downcast<SVGElement>(child);
2408 return isSVGSVGElement(childElement) && childElement.isValid();
2413 #if ENABLE(FULLSCREEN_API)
2414 void Element::webkitRequestFullscreen()
2416 document().requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, Document::EnforceIFrameAllowFullScreenRequirement);
2419 void Element::webkitRequestFullScreen(unsigned short flags)
2421 document().requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), Document::EnforceIFrameAllowFullScreenRequirement);
2424 bool Element::containsFullScreenElement() const
2426 return hasRareData() && elementRareData()->containsFullScreenElement();
2429 void Element::setContainsFullScreenElement(bool flag)
2431 ensureElementRareData().setContainsFullScreenElement(flag);
2432 setNeedsStyleRecalc(SyntheticStyleChange);
2435 static Element* parentCrossingFrameBoundaries(Element* element)
2438 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
2441 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2443 Element* element = this;
2444 while ((element = parentCrossingFrameBoundaries(element)))
2445 element->setContainsFullScreenElement(flag);
2449 #if ENABLE(POINTER_LOCK)
2450 void Element::requestPointerLock()
2452 if (document().page())
2453 document().page()->pointerLockController().requestPointerLock(this);
2457 SpellcheckAttributeState Element::spellcheckAttributeState() const
2459 const AtomicString& value = fastGetAttribute(HTMLNames::spellcheckAttr);
2460 if (value == nullAtom)
2461 return SpellcheckAttributeDefault;
2462 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2463 return SpellcheckAttributeTrue;
2464 if (equalIgnoringCase(value, "false"))
2465 return SpellcheckAttributeFalse;
2467 return SpellcheckAttributeDefault;
2470 bool Element::isSpellCheckingEnabled() const
2472 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2473 switch (element->spellcheckAttributeState()) {
2474 case SpellcheckAttributeTrue:
2476 case SpellcheckAttributeFalse:
2478 case SpellcheckAttributeDefault:
2486 RenderNamedFlowFragment* Element::renderNamedFlowFragment() const
2488 if (renderer() && renderer()->isRenderNamedFlowFragmentContainer())
2489 return toRenderBlockFlow(renderer())->renderNamedFlowFragment();
2494 #if ENABLE(CSS_REGIONS)
2496 bool Element::shouldMoveToFlowThread(const RenderStyle& styleToUse) const
2498 #if ENABLE(FULLSCREEN_API)
2499 if (document().webkitIsFullScreen() && document().webkitCurrentFullScreenElement() == this)
2503 if (isInShadowTree())
2506 if (!styleToUse.hasFlowInto())
2512 const AtomicString& Element::webkitRegionOverset() const
2514 document().updateLayoutIgnorePendingStylesheets();
2516 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2517 if (!document().cssRegionsEnabled() || !renderNamedFlowFragment())
2518 return undefinedState;
2520 switch (regionOversetState()) {
2522 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2526 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2529 case RegionOverset: {
2530 DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2531 return overflowState;
2533 case RegionUndefined:
2534 return undefinedState;
2537 ASSERT_NOT_REACHED();
2538 return undefinedState;
2541 Vector<RefPtr<Range>> Element::webkitGetRegionFlowRanges() const
2543 Vector<RefPtr<Range>> rangeObjects;
2544 if (!document().cssRegionsEnabled())
2545 return rangeObjects;
2547 document().updateLayoutIgnorePendingStylesheets();
2548 if (renderer() && renderer()->isRenderNamedFlowFragmentContainer()) {
2549 RenderNamedFlowFragment* namedFlowFragment = toRenderBlockFlow(renderer())->renderNamedFlowFragment();
2550 if (namedFlowFragment->isValid())
2551 namedFlowFragment->getRanges(rangeObjects);
2554 return rangeObjects;
2560 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2562 if (name == HTMLNames::styleAttr)
2566 return !downcast<SVGElement>(*this).isAnimatableAttribute(name);
2572 #ifdef DUMP_NODE_STATISTICS
2573 bool Element::hasNamedNodeMap() const
2575 return hasRareData() && elementRareData()->attributeMap();
2579 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2581 if (!isInTreeScope())
2584 if (oldName == newName)
2587 updateNameForTreeScope(treeScope(), oldName, newName);
2591 if (!document().isHTMLDocument())
2593 updateNameForDocument(toHTMLDocument(document()), oldName, newName);
2596 void Element::updateNameForTreeScope(TreeScope& scope, const AtomicString& oldName, const AtomicString& newName)
2598 ASSERT(oldName != newName);
2600 if (!oldName.isEmpty())
2601 scope.removeElementByName(*oldName.impl(), *this);
2602 if (!newName.isEmpty())
2603 scope.addElementByName(*newName.impl(), *this);
2606 void Element::updateNameForDocument(HTMLDocument& document, const AtomicString& oldName, const AtomicString& newName)
2608 ASSERT(oldName != newName);
2610 if (WindowNameCollection::elementMatchesIfNameAttributeMatch(*this)) {
2611 const AtomicString& id = WindowNameCollection::elementMatchesIfIdAttributeMatch(*this) ? getIdAttribute() : nullAtom;
2612 if (!oldName.isEmpty() && oldName != id)
2613 document.removeWindowNamedItem(*oldName.impl(), *this);
2614 if (!newName.isEmpty() && newName != id)
2615 document.addWindowNamedItem(*newName.impl(), *this);
2618 if (DocumentNameCollection::elementMatchesIfNameAttributeMatch(*this)) {
2619 const AtomicString& id = DocumentNameCollection::elementMatchesIfIdAttributeMatch(*this) ? getIdAttribute() : nullAtom;
2620 if (!oldName.isEmpty() && oldName != id)
2621 document.removeDocumentNamedItem(*oldName.impl(), *this);
2622 if (!newName.isEmpty() && newName != id)
2623 document.addDocumentNamedItem(*newName.impl(), *this);
2627 inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2629 if (!isInTreeScope())
2635 updateIdForTreeScope(treeScope(), oldId, newId);
2639 if (!document().isHTMLDocument())
2641 updateIdForDocument(toHTMLDocument(document()), oldId, newId, UpdateHTMLDocumentNamedItemMapsOnlyIfDiffersFromNameAttribute);
2644 void Element::updateIdForTreeScope(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
2646 ASSERT(isInTreeScope());
2647 ASSERT(oldId != newId);
2649 if (!oldId.isEmpty())
2650 scope.removeElementById(*oldId.impl(), *this);
2651 if (!newId.isEmpty())
2652 scope.addElementById(*newId.impl(), *this);
2655 void Element::updateIdForDocument(HTMLDocument& document, const AtomicString& oldId, const AtomicString& newId, HTMLDocumentNamedItemMapsUpdatingCondition condition)
2657 ASSERT(inDocument());
2658 ASSERT(oldId != newId);
2660 if (WindowNameCollection::elementMatchesIfIdAttributeMatch(*this)) {
2661 const AtomicString& name = condition == UpdateHTMLDocumentNamedItemMapsOnlyIfDiffersFromNameAttribute && WindowNameCollection::elementMatchesIfNameAttributeMatch(*this) ? getNameAttribute() : nullAtom;
2662 if (!oldId.isEmpty() && oldId != name)
2663 document.removeWindowNamedItem(*oldId.impl(), *this);
2664 if (!newId.isEmpty() && newId != name)
2665 document.addWindowNamedItem(*newId.impl(), *this);
2668 if (DocumentNameCollection::elementMatchesIfIdAttributeMatch(*this)) {
2669 const AtomicString& name = condition == UpdateHTMLDocumentNamedItemMapsOnlyIfDiffersFromNameAttribute && DocumentNameCollection::elementMatchesIfNameAttributeMatch(*this) ? getNameAttribute() : nullAtom;
2670 if (!oldId.isEmpty() && oldId != name)
2671 document.removeDocumentNamedItem(*oldId.impl(), *this);
2672 if (!newId.isEmpty() && newId != name)
2673 document.addDocumentNamedItem(*newId.impl(), *this);
2677 void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2679 ASSERT(hasTagName(labelTag));
2684 if (oldForAttributeValue == newForAttributeValue)
2687 if (!oldForAttributeValue.isEmpty())
2688 scope.removeLabel(*oldForAttributeValue.impl(), *toHTMLLabelElement(this));
2689 if (!newForAttributeValue.isEmpty())
2690 scope.addLabel(*newForAttributeValue.impl(), *toHTMLLabelElement(this));
2693 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2695 if (name == HTMLNames::idAttr)
2696 updateId(oldValue, newValue);
2697 else if (name == HTMLNames::nameAttr)
2698 updateName(oldValue, newValue);
2699 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2700 if (treeScope().shouldCacheLabelsByForAttribute())
2701 updateLabel(treeScope(), oldValue, newValue);
2704 if (oldValue != newValue) {
2705 auto styleResolver = document().styleResolverIfExists();
2706 if (styleResolver && styleResolver->hasSelectorForAttribute(*this, name.localName()))
2707 setNeedsStyleRecalc();
2710 if (std::unique_ptr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
2711 recipients->enqueueMutationRecord(MutationRecord::createAttributes(*this, name, oldValue));
2713 #if ENABLE(INSPECTOR)
2714 InspectorInstrumentation::willModifyDOMAttr(&document(), this, oldValue, newValue);
2718 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2720 attributeChanged(name, nullAtom, value);
2721 InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
2722 dispatchSubtreeModifiedEvent();
2725 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2727 attributeChanged(name, oldValue, newValue);
2728 InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), newValue);
2729 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2732 void Element::didRemoveAttribute(const QualifiedName& name, const AtomicString& oldValue)
2734 attributeChanged(name, oldValue, nullAtom);
2735 InspectorInstrumentation::didRemoveDOMAttr(&document(), this, name.localName());
2736 dispatchSubtreeModifiedEvent();
2739 PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2741 if (HTMLCollection* collection = cachedHTMLCollection(type))
2744 RefPtr<HTMLCollection> collection;
2745 if (type == TableRows) {
2746 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLTableRowsCollection>(toHTMLTableElement(*this), type);
2747 } else if (type == SelectOptions) {
2748 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLOptionsCollection>(toHTMLSelectElement(*this), type);
2749 } else if (type == FormControls) {
2750 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2751 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLFormControlsCollection>(*this, type);
2753 return ensureRareData().ensureNodeLists().addCachedCollection<HTMLCollection>(*this, type);
2756 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2758 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cachedCollection<HTMLCollection>(type) : 0;
2761 IntSize Element::savedLayerScrollOffset() const
2763 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2766 void Element::setSavedLayerScrollOffset(const IntSize& size)
2768 if (size.isZero() && !hasRareData())
2770 ensureElementRareData().setSavedLayerScrollOffset(size);
2773 PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2775 if (auto* attrNodeList = attrNodeListForElement(*this))
2776 return findAttrNodeInList(*attrNodeList, name);
2780 PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2782 auto& attrNodeList = ensureAttrNodeListForElement(*this);
2783 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2785 attrNode = Attr::create(this, name);
2786 treeScope().adoptIfNeeded(attrNode.get());
2787 attrNodeList.append(attrNode);
2789 return attrNode.release();
2792 void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2794 ASSERT(hasSyntheticAttrChildNodes());
2795 attrNode->detachFromElementWithValue(value);
2797 auto* attrNodeList = attrNodeListForElement(*this);
2798 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2799 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2800 attrNodeList->remove(i);
2801 if (attrNodeList->isEmpty())
2802 removeAttrNodeListForElement(*this);
2806 ASSERT_NOT_REACHED();
2809 void Element::detachAllAttrNodesFromElement()
2811 auto* attrNodeList = attrNodeListForElement(*this);
2812 ASSERT(attrNodeList);
2814 for (const Attribute& attribute : attributesIterator()) {
2815 if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute.name()))
2816 attrNode->detachFromElementWithValue(attribute.value());
2819 removeAttrNodeListForElement(*this);
2822 void Element::resetComputedStyle()
2824 if (!hasRareData() || !elementRareData()->computedStyle())
2827 auto reset = [](Element& element) {
2828 if (!element.hasRareData() || !element.elementRareData()->computedStyle())
2830 if (element.hasCustomStyleResolveCallbacks())
2831 element.willResetComputedStyle();
2832 element.elementRareData()->resetComputedStyle();
2835 for (auto& child : descendantsOfType<Element>(*this))
2839 void Element::clearStyleDerivedDataBeforeDetachingRenderer()
2841 unregisterNamedFlowContentElement();
2842 cancelFocusAppearanceUpdate();
2843 clearBeforePseudoElement();
2844 clearAfterPseudoElement();
2847 ElementRareData* data = elementRareData();
2848 data->resetComputedStyle();
2849 data->resetDynamicRestyleObservations();
2852 void Element::clearHoverAndActiveStatusBeforeDetachingRenderer()
2854 if (!isUserActionElement())
2857 document().hoveredElementDidDetach(this);
2858 if (inActiveChain())
2859 document().elementInActiveChainDidDetach(this);
2860 document().userActionElements().didDetach(this);
2863 bool Element::willRecalcStyle(Style::Change)
2865 ASSERT(hasCustomStyleResolveCallbacks());
2869 void Element::didRecalcStyle(Style::Change)
2871 ASSERT(hasCustomStyleResolveCallbacks());
2874 void Element::willResetComputedStyle()
2876 ASSERT(hasCustomStyleResolveCallbacks());
2879 void Element::willAttachRenderers()
2881 ASSERT(hasCustomStyleResolveCallbacks());
2884 void Element::didAttachRenderers()
2886 ASSERT(hasCustomStyleResolveCallbacks());
2889 void Element::willDetachRenderers()
2891 ASSERT(hasCustomStyleResolveCallbacks());
2894 void Element::didDetachRenderers()
2896 ASSERT(hasCustomStyleResolveCallbacks());
2899 PassRefPtr<RenderStyle> Element::customStyleForRenderer(RenderStyle&)
2901 ASSERT(hasCustomStyleResolveCallbacks());
2905 void Element::cloneAttributesFromElement(const Element& other)
2907 if (hasSyntheticAttrChildNodes())
2908 detachAllAttrNodesFromElement();
2910 other.synchronizeAllAttributes();
2911 if (!other.m_elementData) {
2912 m_elementData.clear();
2916 // 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.
2917 // Fortunately, those named item maps are only updated when this element is in the document, which should never be the case.
2918 ASSERT(!inDocument());
2920 const AtomicString& oldID = getIdAttribute();
2921 const AtomicString& newID = other.getIdAttribute();
2923 if (!oldID.isNull() || !newID.isNull())
2924 updateId(oldID, newID);
2926 const AtomicString& oldName = getNameAttribute();
2927 const AtomicString& newName = other.getNameAttribute();
2929 if (!oldName.isNull() || !newName.isNull())
2930 updateName(oldName, newName);
2932 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
2933 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes.
2934 if (other.m_elementData->isUnique()
2935 && !other.m_elementData->presentationAttributeStyle()
2936 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
2937 const_cast<Element&>(other).m_elementData = toUniqueElementData(other.m_elementData)->makeShareableCopy();
2939 if (!other.m_elementData->isUnique())
2940 m_elementData = other.m_elementData;
2942 m_elementData = other.m_elementData->makeUniqueCopy();
2944 for (const Attribute& attribute : attributesIterator())
2945 attributeChanged(attribute.name(), nullAtom, attribute.value(), ModifiedByCloning);
2948 void Element::cloneDataFromElement(const Element& other)
2950 cloneAttributesFromElement(other);
2951 copyNonAttributePropertiesFromElement(other);
2954 void Element::createUniqueElementData()
2957 m_elementData = UniqueElementData::create();
2959 m_elementData = toShareableElementData(m_elementData)->makeUniqueCopy();
2962 bool Element::hasPendingResources() const
2964 return hasRareData() && elementRareData()->hasPendingResources();
2967 void Element::setHasPendingResources()
2969 ensureElementRareData().setHasPendingResources(true);
2972 void Element::clearHasPendingResources()
2974 ensureElementRareData().setHasPendingResources(false);
2977 bool Element::canContainRangeEndPoint() const
2979 return !equalIgnoringCase(fastGetAttribute(roleAttr), "img");
2982 String Element::completeURLsInAttributeValue(const URL& base, const Attribute& attribute) const
2984 return URL(base, attribute.value()).string();
2987 } // namespace WebCore