skip to Main Content

I have looped through my posts and the result is multiple posts on a summary page. I am also using firebase realtime database to store certain info for these posts. I am querying the firebase realtime database to see what data is stored under a post id.
Unfortunately I am only getting a result for the 1st post and subsequent posts aren’t getting any data.

After some research I have learned that you cannot choose multiple div’s with the same ID as ID’s are supposed to be unique on the HTML page.

The original script is

    document.getElementById().title

I have tried the following:

      document.getElementsByName().title
      document.getElementsByClass().title
     

but these syntax are not right. Any advice as to how I can shape my query to get the desired result.

2

Answers


  1. It will be document.getElementsByClassName().title instead of document.getElementsByClass().title

    Login or Signup to reply.
  2. Try document.querySelectorAll(".className") to select all the elements on a page that fit the specified criteria. document.querySelector and document.querySelectorAll both target elements using the css-like keywords.

    Then you could loop through all the elements that it returns:

    let postList = document.querySelectorAll(".post-class-name")
    
    for (let i = 0; i < postList.length; i++)
        console.log(postList[i].title)
        // Will log the title of each post
    

    However, please note that the title attribute is the text that appears after hovering on an element. Maybe add a class to each of the titles called post-title and replacing .post-class-name with .post-title and then instead of finding postList[i].title you could find postList[i].innerText which will return the title of each post’s title

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search