Suppose we use JSON API Tumblr well or any kind of flight. And when we get the value of photo-caption through jquery, we get the content of the records in this format:

<p id="name">Test</p><p id="date">01.01.2021</p><p id="about">Bla Bla Bla</p> 

And further on Json there is another post with the same result:

 <p id="name">Test 2</p><p id="date">02.01.2021</p><p id="about">Bla Bla Bla</p> 

So how do we get the name values ​​in a separate variable?

    2 answers 2

     var s = '<p id="name">Test</p><p id="date">01.01.2021</p><p id="about">Bla Bla Bla</p>'; var $wrapper = $('<div>').html(s); console.log($wrapper.find('#date').text()); 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

    You can do without an additional element, but then you have to look in different ways for nested and top-level elements and elements:

     var s = '<p id="name">Test</p><p id="date">01.01.2021</p><p id="about">Bla <span id="s">Bla</span> Bla</p>'; var $els = $(s); console.log($els.filter('#date').text()); console.log($els.find('#s').text()); 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

    • @ Mr.Black for an additional underscore that this is a jquery-object, and reduce porridge in the head of those who will read the code - andreymal
    • Tell me how you can implement a search for an object, let's say we have a lot of such, and we want to display an object whose name = "test" - arthru
    • @arthru, by attribute selector: [name="test"] . - Qwertiy
    • Can I have a code sample? - arthru
    • @arthru, and look at the jQuery website? - Qwertiy

    From json, we have a string, so we will create an element on it, and then we will get the selector to the desired value by the attribute

     e = document.createElement('p'); e.innerHTML = '<p id="name">Test</p><p id="date">01.01.2021</p><p id="about">Bla Bla Bla</p>'; name = e.querySelector('#name').innerText; date = e.querySelector('#date').innerText; about = e.querySelector('#about').innerText; console.log(name, date, about); 

     json = $('<p>').html( '<p id="name">Test</p><p id="date">01.01.2021</p><p id="about">Bla Bla Bla</p>' + '<p id="name">Test 2</p><p id="date">02.01.2021</p><p id="about">Bla Bla Bla</p>' ); name1 = json.find('#name').eq(0).text(); name2 = json.find('#name').eq(1).text(); console.log(name1); console.log(name2); 
     <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>