Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery select element in shadow DOM

HTML code:

<textarea name="remark" rows="4" cols="30">
  #shadow-root (user-agent)
  <div id="inner-editor">
    "this is text in textarea"
  </div>
</textarea>

I am trying select element DIV with id="inner-editor" with this JQuery:

var el = $("[name='remark']").children();

but the var el is empty. If I try this:

$("[name='remark']").text();

It is also empty output.

#shadow-root (user-agent) is something like template (I dont know exactle what it is) and isn't display in textarea

Is it possible select this element DIV in textarea element?

like image 892
Balio Avatar asked Mar 23 '15 17:03

Balio


People also ask

How do you access the element in shadow DOM?

We can only access the shadow DOM by the reference returned by attachShadow (and probably hidden inside a class). Browser-native shadow trees, such as <input type="range"> , are closed. There's no way to access them.

What selector works for shadow DOM elements?

The :host selector allows to select the shadow host (the element containing the shadow tree).

How do you scrape a shadow DOM page?

So instead of that, we can replace the content of each element containing shadow DOM with the HTML of shadow DOM. // Iterate over all elements in the main DOM. // content with the HTML of shadow DOM. After you run this, you can access all the elements and content easily using jQuery or plain JavaScript.

Is iframe a shadow DOM?

While iframes were the only solution for a long time, these days we have the shadow DOM. If you need a basic explainer, I've written about web components in the past. Part of the web component spec is the shadow DOM. The shadow DOM lets us define a “shadow root”.


2 Answers

I dont really get your example, but i guess you are hiding <div id="inner-editor">in the Shadow Root of the <textarea name="remark" rows="4" cols="30">.

You need to select the <textarea name="remark" rows="4" cols="30"> and there you can access the Shadow Root of the element via the shadowRoot javascript property.

Full example:

var el = $("[name='remark']").shadowRoot.getElementById("inner-editor");

Edit: With Jquery, according to your question, you need to pass the shadowRoot to Jquery. It should work with Jquery as well:

var sr = $("[name='remark']").shadowRoot;
var el = $(sr).find("#inner-editor");
like image 104
Tobi Avatar answered Sep 30 '22 23:09

Tobi


This worked for me to select an element within Shadow root. I have converted it to your scenario.

let textArea = $("textarea[name='remark']"); 
let sr = $(textArea)[0].shadowRoot; 
console.log($(sr).find('.#inner-editor'));

Hope this may help somebody.

like image 30
Shwetha Avatar answered Oct 01 '22 01:10

Shwetha