Home > Mobile >  Select elements using only the tag name
Select elements using only the tag name

Time:10-04

I have this simple html document:

    <header>
      <div><p>Fail</p></div>
      <p>Success!</p>
    </header>

How can I select the second paragraph using just the tag name. I don't want to use something like this:

let successParagraph = document
   .getElementsByTagName("header")[0]
   .getElementsByTagName("p")[1];

because if I will insert another div that contains a paragraph I will have to change the children's number.

If I use something like this it doesn't work:

let successParagraph = document.getElementsByTagName("header > p");

CodePudding user response:

You cannot using getElementsByTagName

  1. by passing anything other than a tag name as a parameter
  2. to get a single element.(It always returns a collection or null)

Syntax: getElementsByTagName(tagName)

Parameters
tagName is the qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used.

Return value
A live HTMLCollection of elements with a matching tag name, in the order they appear. If no elements are found, the HTMLCollection is empty.

As you can see from the documentation, the function expects a qualified name to look for, not something like header > p

Also the return type is HtmlCollection | null. It cannot select an element anyway.


The best option available is to use document.querySelector

const elm = document.querySelector('header > p');
console.log(elm);
<header>
  <div><p>Fail</p></div>
  <p>Success!</p>
</header>

CodePudding user response:

const secondElement = document.querySelectorAll('header p');

if (secondElement[1]) {
  let successParagraph = secondElement[1].innerHTML;
  console.log(successParagraph); // Success!
};
<header>
    <div><p>Fail</p></div>
    <p>Success!</p>
 </header>

CodePudding user response:

you can use querySelectorAll

const paragraphs = document.querySelectorAll("p");

paragraphs[1] would be the second one.

  • Related