简体   繁体   中英

Inner text from an element witout and element

I have this code:

<span class="start-end">
<duration>October </duration>
– December (1 duration)
</span>

and another one:

<span class="start-end">
<duration>September 2010</duration>
–
<duration>June 2014</duration>
(2 duration)
</span>

Generally I can use the following selector to take the result from an inner text inside and element like this:

document.querySelector('span.start-end duration').innerHTML

for October from the first block of code and September 2010 for the second block.

How can I get the value from first block December (1 duration) and from the second block the June 2014 and using another command take the (2 duration)

(2 duration) is the text of the .start-end span. I would use

document.querySelector(span.start-end).textContent;

您可以使用:nth-child来获取任何子元素(或本例中的:last-child ):

document.querySelector('span.start-end duration:nth-child(2)').innerHTML

 var spans = document.getElementsByClassName("start-end") for (var k in spans) { var span = spans[k] var durations = span.getElementsByTagName("duration") if(durations.length == 1) { console.log(durations[0].innerHTML) } else if(durations.length == 2) { console.log(durations[0].innerHTML, durations[1].innerHTML) } } 
 <span class="start-end"> <duration>October </duration> – December (1 duration) </span> and another one: <span class="start-end"> <duration>September 2010</duration> – <duration>June 2014</duration> (2 duration) </span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM