0

I have html string data inside variable like this

 var htmlstring = "<div><div class='testdiv'>924422</div></div>"

What I am expecting is to fetch content of div having class.In this example .testdiv data.

How can I achieve?.

I know one approach: Append this html string to html page and then access.But I dont want to do it as I am using ajax and server returning kind of html string.Now I want to fetch data inside specific div.

So is there any alternative way to do?

3 Answers 3

3

First you don't use . in class name in html. And to fetch the content of that div in html string, you could use jquery find function.

var htmlstring = "<div><div class='testdiv'>924422</div></div>"
alert($(htmlstring).find('.testdiv').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Comments

2

Here's a way you can achieve it without jQuery.

var htmlstring = "<div><div class='testdiv'>924422</div></div>";

function getTestDiv(htmlString) {
  var textVal = null;
  var div = document.createElement('div');
  div.innerHTML = htmlString;
  var elements = div.childNodes;
  if (elements.item(0).childNodes.item(0).className === 'testdiv') {
    textVal = elements.item(0).childNodes.item(0).innerHTML;
  }
  return textVal;
}

console.log(getTestDiv(htmlstring));

Comments

0

You can do this by :

console.log($(htmlstring).find("div.testdiv").text());

2 Comments

String has no method find()
Yup, just forgot the $ sign

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.