Reputation: 23285
How can I select the paragraph that's within a paragraph, without a class or ID to identify it?
<!DOCTYPE html>
...
<body>
<h1>Hello</h1>
<h2>Goodbye</h2>
<ul>
<li id="highlight">List Item 1</li>
<li class="som">List Item 2</li>
<li class="bolded">List Item 3</li>
<li class="bolded">List Item 4 <p>Testing123</p></li>
</ul>
<p>
This is an <strong>awesome</strong> paragraph!
</p>
<a href="htps://www.google.com">Link to Google</a>
<a href="https://www.bing.com">Link to Bing</a>
<p>
Click a button!
<button class="button">Click here!</button>
<p>Haven't been clicked...</p>
</p>
<script type="text/javascript" src="domManipulate.js"></script>
</body>
</html>
How do I select the <p>Haven't been clicked...</p>
tags?
I've tried var under_btn_txt = document.querySelector("p p");
and ... = document.getElementsByTagName("p")
.
I'd think the first works, because document.querySelector("li p");
does get the Testing123
text...
The second method does, technically, get it. I need to access it with, say under_btn_txt[2]
. But what if I don't know necessarily what p
that's in, to know I need the second index?
Upvotes: 0
Views: 215
Reputation: 22574
A paragraph element may not contain other block elements. That means you can't nest p
inside another p
tag, since p
is block elements.
You have to modify your HTML. You can replace parent p
with div
and access p
tag inside it using div p
.
console.log(document.querySelectorAll('div p')[0])
<h1>Hello</h1>
<h2>Goodbye</h2>
<ul>
<li id="highlight">List Item 1</li>
<li class="som">List Item 2</li>
<li class="bolded">List Item 3</li>
<li class="bolded">List Item 4 <p>Testing123</p></li>
</ul>
<p>
This is an <strong>awesome</strong> paragraph!
</p>
<a href="htps://www.google.com">Link to Google</a>
<a href="https://www.bing.com">Link to Bing</a>
<div>
Click a button!
<button class="button">Click here!</button>
<p>Haven't been clicked...</p>
</div>
Upvotes: 1
Reputation: 50346
The html here is invalid. p
is a self closing tag and it cannot nest another p
.More information here.
Add a class to the parent p element and for nesting use span
.Then use querySelector
and getElementsByTagName
& innerHTML
to get the content
var getPTag = document.querySelector(".click");
var getChild = getPTag.getElementsByTagName('span')[0].innerHTML;
console.log(getChild)
<h1>Hello</h1>
<h2>Goodbye</h2>
<ul>
<li id="highlight">List Item 1</li>
<li class="som">List Item 2</li>
<li class="bolded">List Item 3</li>
<li class="bolded">List Item 4
<p>Testing123</p>
</li>
</ul>
<p>
This is an <strong>awesome</strong> paragraph!
</p>
<a href="htps://www.google.com">Link to Google</a>
<a href="https://www.bing.com">Link to Bing</a>
<p class="click">Click a button!<button class="button">Click here!</button>
<span>Haven't been clicked...</span>
</p>
Upvotes: 1