newsshare24h
newsshare24h

Reputation: 69

How to get text in html tag

i'm trying to get "some text" in <p> tag, i can't use .text() because it get all text in <b> tag

<p><b class="title">Title: </b> some text </p>

$('p').text() // result is: "Title: some text"

I just want to get some text

Upvotes: 2

Views: 3548

Answers (3)

leocabrallce
leocabrallce

Reputation: 322

You have to remove this piece of text ...

var p = document.querySelector("p").textContent
var b = document.querySelector("p > b").textContent

console.log(p.replace(b, "").trim())
<p>
  <b class="title">Title: </b> some text 
</p>

... or specify what you're trying to get

var p = document.querySelector("p > spam#foo").textContent.trim()

console.log(p)
<p>
  <b>Text: </b> <spam id="foo">some text</spam>
</p>

Upvotes: 2

nazifa rashid
nazifa rashid

Reputation: 1504

$('p').click(function () {
    $('#newText').html((this.childNodes[1].nodeValue))
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <p><b class="title">Title: </b> some text </p>
  <h1 id="newText"></h1>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>

The simplest way to not get the text of the child. Hope it'd help

Upvotes: 0

kyun
kyun

Reputation: 10264

/* get whole text from <p/> tag*/
console.log($('p').text());

/* get partial text from <b/> tag*/
console.log($('p > b').text());

/* split text from <b/> to whole text */
console.log($('p').text().split($('p > b').text())[1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><b class="title">Title: </b> some text </p>

Upvotes: 3

Related Questions