user8758206
user8758206

Reputation: 2191

Simple way of determining whether a node contains a p tag

I'm trying to determing whether a div contains a specific node (in this case, p node). I don't know why but my simple JS isn't working.

Could someone explain why this isn't working?

Codepen: https://codepen.io/ns91/pen/OJJxZRb

let test = document.querySelector('div');

if (test.contains('P')) {
  console.log('has a p');
} else {
  console.log('has no ps');
}
<div>
  <h1>header</h1>
  <p>para</p>
  <p>para</p>
  <span>span</span>
  <p>para</p>
</div>

Upvotes: 0

Views: 776

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50759

When using the contains you need to pass through a node, however, you're passing through a string and so you're getting an error. The node you pass through must be a reference to a node in the node's childNodes. So, something like this will also fail:

const test = document.querySelector('div');
const p = document.createElement('p'); // create a p node
// check if testt has a child-node which references the same node we created above, this isn't the case, so it will fail
if (test.contains(p)) { 
  console.log('has a p');
} else {
  console.log('has no ps');
}
<div>
  <h1>header</h1>
  <p>para</p>
  <p>para</p>
  <span>span</span>
  <p>para</p>
</div>

Instead, you could change your selector to select p tags inside div tags, and then check whether or not your querySelector found a value using your if statement:

const test = document.querySelector('div p');
if (test) {
  console.log('has a p');
} else {
  console.log('has no ps');
}
<div>
  <h1>header</h1>
  <p>para</p>
  <p>para</p>
  <span>span</span>
  <p>para</p>
</div>

Upvotes: 1

Greedo
Greedo

Reputation: 3549

Your code doesn't work because variable test is not a plain text, so contains does not work in your code

let test = document.querySelector('div').querySelector('p');

if (test) {
  console.log('has a p');
} else {
  console.log('has no ps');
}
<div>
  <h1>header</h1>
  <p>para</p>
  <p>para</p>
  <span>span</span>
  <p>para</p>
</div>

Upvotes: 1

Rajesh
Rajesh

Reputation: 24925

As commented use

test.querySelector('p')

test.contains('P') is

let test = document.querySelector('div');
const pTag = test.querySelector('p');

if (pTag !== null) {
  console.log('has a p');
} else {
  console.log('has no ps');
}
<div>
  <h1>header</h1>
  <p>para</p>
  <p>para</p>
  <span>span</span>
  <p>para</p>
</div>

If you wish to use Node.contains, please refer docs. It expects argument as Node and not string

let test = document.querySelector('div');
const p = document.querySelector('.pTag')

if (test.contains( p )) {
  console.log('has a p');
} else {
  console.log('has no ps');
}
<div>
  <h1>header</h1>
  <p>para</p>
  <p class='pTag'>para</p>
  <span>span</span>
  <p>para</p>
</div>

Upvotes: 1

Related Questions