0

I have some HTML data stored on JavaScript variable and I want to fetch the data from that variable

I'm trying to get it by getElementById() method. Please also keep it in mind that I have used same id in every div. I know it's not good way but there is some restriction. So I need the data from 2nd Div.

var complexArray = "<div id="
post ">First content<\/div><div id="
post ">Second Content<\/div><div id="
post ">Third Content<\/div>";

var data = document.getElementById('post').innerHTML;
alert(data);

2
  • 1
    You can't use the same ID in every div, it's invalid and won't work. Use 'Classes' instead to achieve the desired result. Commented Jun 27, 2019 at 11:04
  • document.getElementById, unsurprisingly, searches the document, not some random string of HTML. Commented Jun 27, 2019 at 11:05

2 Answers 2

2

You can't query in the document for something that only exists in a string variable.

Put that html string into a temporary element and query for it within that element

Change the repeating ID's to classes instead since ID's must be unique

var complexArray = '<div class="post">First content<\/div><div class="post">Second Content<\/div><div class="post">Third Content<\/div>';

// create element to insert the html string into
var tempDiv = document.createElement('div');
tempDiv.innerHTML = complexArray;

// query within that element
var posts = tempDiv.querySelectorAll('.post');

var data = posts[1].innerHTML;
console.log(data);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use DOM PARSER.And id should be unique for Every element,as you have use same id for multiple elements,which is wrong.I have change from id to class ,with post id is only for first element

var complexArray = "<div id='post' class='post'>First content<\/div><div class='post'>Second Content<\/div><div class='post'>Third Content<\/div>";

let doc = new DOMParser().parseFromString(complexArray, "text/html");
console.log(doc.getElementById('post').innerHTML); //
/// query selector All for all elements

doc.querySelectorAll('.post').forEach((ele, i) => {
  if (i == 1) {
    console.log(ele.innerHTML)
  }

})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.