Reputation: 47
How can I access child element's innerHTML
which has no class nor ID through parent element with class in JavaScript?
It should return only text
between <b>
tags.
<div class="parent element">
<h5>
some other text<b>text</b>
</h5>
</div>
Upvotes: 3
Views: 1961
Reputation: 87201
You can use document.querySelector()
with a CSS selector like .parent.element h5 b
, which will find a b
tag, inside a h5
tag, inside an element with the classes parent
and element
.
Then you can use textContent
to grab text only, or innerHTML
to grab both text and markup.
console.log(document.querySelector('.parent.element h5 b').textContent);
// sample when using innerHTML grabbing the h5
console.log(document.querySelector('.parent.element h5').innerHTML);
// sample when using textContent grabbing the h5
console.log(document.querySelector('.parent.element h5').textContent);
<div class="parent element">
<h5>
some other text<b>text</b>
</h5>
</div>
A note when it comes to textContent
vs innerText
:
Internet Explorer introduced
node.innerText
. The intention is similar tonode.textContent
but with the following differences:
While
textContent
gets the content of all elements, including<script>
and<style>
elements,innerText
does not.
innerText
is aware of style and will not return the text of hidden elements, whereastextContent
will.As
innerText
is aware of CSS styling, it will trigger a reflow, whereastextContent
will not.Unlike
textContent
, alteringinnerText
in Internet Explorer (up to version 11 inclusive) not only removes child nodes from the element, but also permanently destroys all descendant text nodes (so it is impossible to insert the nodes again into any other element or into the same element anymore).
Upvotes: 3
Reputation: 280
var innerText=document.querySelector('.parent.element h5 b').innerText
console.log(innerText);
<div class="parent element">
<h5>
some other text<b>text</b>
</h5>
</div>
Upvotes: 5
Reputation: 68943
Try with querySelector() and textContent
:
var txt = document.querySelector('.parent.element > h5 > b').textContent;
console.log(txt)
<div class="parent element">
<h5>
some other text<b>text</b>
</h5>
</div>
Upvotes: 3