I would like to know how to dynamically retrieve the content text of a HTML tag and its child tags?
Here is my HTML code, for example:
<p><code>C:<select>
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>test3<select>
<option value="test4">test4</option>
<option value="test5">test5</option>
</select>test6<select>
<option value="test7">test7</option>
<option value="test8">test8</option>
<option value="test9">test9</option>
</select>test10.txt</code></p>
I would like to create a button after this code, and when it is clicked, I would like to write the content directly within the console.
For example:
C:test2test3test4test6test8test10.txt
or
C:test1test3test5test6test9test10.txt
…
It might be possible that another paragraph of code only contains 1 or 2 <select>
tags. So, I don’t want a code that only works for 3 <select>
tags, like in the previous example.
Thank you very much in advance
2
Answers
The best property to use if you want all the text (ie. both inside and outside the
<select>
elements) is.textContent
:Working Example:
Further Reading on
textContent
vsinnerText
:The source above states:
Differences from innerText
Don’t get confused by the differences between
Node.textContent
andHTMLElement.innerText
. Although the names seem similar, there are important differences:textContent
gets the content of all elements, including<script>
and<style>
elements. In contrast,innerText
only shows "human-readable" elements.textContent
returns every element in the node. In contrast,innerText
is aware of styling and won’t return the text of "hidden" elements.Moreover, since
innerText
takes CSS styles into account, reading the value ofinnerText
triggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)Further Reading on
selectedOptions
:I think the best way will be to use select even for c:, test3… and just change their appearance not to look as a select field (using ‘noselect’ class). Then you will need to use the selected attribute to be able to get the default value of the unchanged Select HTML tag. Then I first get all the default value and look for the changed Select tag with corresponding eventListener and finaly change this value in the defaulValue array using the index