Ke Vin
Ke Vin

Reputation: 87

Find specific text inside a DOM Jquery

I would like find the next sentence after find "battery" string. The text doesn't have tags, only quote marks.

<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah">battery</h2> << using this string "battery"
"coucou test tt test" << text to find
<h2 class="inshallah">dress</h2>
</html>

I tried this but, it doesn't work if there is no tags after

    var test = $('.inshallah').filter(function() {
    return $(this).text().trim() === "battery";
    }).next().text();
    
    console.log(test)

Upvotes: 0

Views: 57

Answers (4)

Pranav Sinha
Pranav Sinha

Reputation: 79

$("html").html().split("battery")[1].split("h2>")[1].split("<h2")[0]

This is not recommended though. You should give proper attributes, like classes, id or data-attributes. Never leave data stranded. It is advised to encase data in some tag (preferably div).

Upvotes: 0

Ram
Ram

Reputation: 144729

You are on the right track. Your code returns dress as .next only selects the next sibling element, what you want to select is the next textNode. jQuery has no API for selecting the next textNode. You can use the DOM HTMLElement.nextSibling property:

var text = $('.inshallah').filter(function() {
    return $(this).text().trim() === "battery";
}).get(0).nextSibling.textContent;

Upvotes: 2

Emeeus
Emeeus

Reputation: 5260

$(document).ready(function() {

  $("h2").each(function(i, e) {//or .inshallah, it's the same
    if (e.innerText == "battery") {
      alert(e.nextSibling.data);
    }
  })

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah">battery</h2>
"coucou test tt test"
<h2 class="inshallah">dress</h2>

</html>

Upvotes: 1

regex
regex

Reputation: 101

You need to specify html dom element p

Solution 1

<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah">battery</h2>
<p>coucou test tt test</p>
<h2 class="inshallah">dres</h2>
</html>

var test = $('.inshallah').filter(function() {
   return $(this).text().trim() === "battery";
}).next().text();

console.log(test)

Solution 2

<html>
<h2 class="inshallah">film</h2>
<h2 class="inshallah battery">battery</h2>
<p>coucou test tt test</p>
<h2 class="inshallah">dress</h2>
</html>

$( ".battery" ).next().css( "background-color", "red" );

I hope you get the idea.

Upvotes: 0

Related Questions