Get text inside an element using javascript - javascript

I am trying to get a text content inside a div using jquery. But it returns 'undefined'. Please someone tell me what i'm doing wrong here. this is my code.
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).textContent;
console.log(text);
});

textContent is a property on native elements, not on jQuery objects. $(this) wraps this (which is a native DOM element) in a jQuery object.
Either stick to the native DOM api (and go with textContent) - which is what I'd recommend:
document.addEventListener('click', (e) => {
if (e.target.classList.contains('exc_text') {
console.log(e.target.textContent);
}
})
Or stick with jQuery if you have to (and use .text()):
$(document).on('click', '.exc_text', function(){
var text = $(this).text();
console.log(text);
});

You're reselecting the element with jQuery which you don't need to do. Try this
$(document).on('click','.exc_text',function(){
var text = this.textContent;
console.log(text);
});
The easiest way to solve this is to look in dev tools. All i did was break on the second link, and hovered over this, which showed me that it was an element so no need to reselect it...

You should use .text() instead of .textContent
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).text();
console.log(text);
});

Just simply use .text()
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text', function(){
var text = $(this).text();
console.log(text);
});

Related

How to change child text only with jQuery?

I got a piece html code like this:
<div><span>span_text</span>div_text</div>
I want to change 'div_text' with jQuery, tried with $.text('changed_div_text') but failed, result like this which is not what I want.
let tmpl = '<div><span>span_text</span>div_text</div>'
let $ = cheerio(tmpl)
console.log($.text()) // span_textdiv_text
$.text('changed_div_text')
console.log($.text()) // changed_div_text
As you can see, text() function will change inner text also, hope someone know a way to solve this problem, thanks!
jQuery doesn't offer a lot of methods that act directly on text nodes. You can use contents to find all child nodes (including text nodes), and you can use filter to find only text nodes, and then you can modify their nodeValue to change their text. Example:
// Get just the text nodes
var textNodes = $("#target").contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
});
// In this case, I just replace the text with "Index n" where n is the index
textNodes.each(function(index) {
this.nodeValue = "Index " + index;
});
<div id="target"><span>span_text</span>div_text</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you have to know the text div_text is the childNode of div,and it is kind of textNode
var div=document.createElement('div');
div.innerHTML='<div><span>span_text</span>div_text</div>';
div.childNodes[0].childNodes[1].textContent='test';
console.log(div.innerHTML);//<div><span>span_text</span>test</div>
if you want to change the text,you can change the value of the textNode,for example,change the textContent ,innerText or innerHTML,,,
your html code is <div><span>span_text</span>div_text</div>
for your understanding I am assuming a button with id btn. clicking this button the text will be changed
button code <button id="btn">change</button>
now if you want to change all the child text of the div then the below code will work fine.
$(document).ready(function(){
$("#btn").click(function(){
$("div > span").text("changed_div_text");
});
});
now if you only want to change the last child of the div then the code is below
$(document).ready(function(){
$("#btn").click(function(){
$("div > span:last-child").text("changed_div_text");
});
});
hope it will solve your issue

How to get value from a dynamic element

I need to get the value from a "p" element, I draw this "p" with jQuery and it's ok, then I have a button and when I click on it I want to display the value from "p" element but I don't get any information, here is a simple code example:
$(document).ready(function() {
$('#c').click(function() {
var p = $('#p1').val();
alert(p);
});
draw();
});
function draw() {
var html = "";
html += '<p id="p1">Hi</p>';
$('#d').html(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="c">Click</button>
<hr />
<div id="d">
</div>
How can I solve this? I don't get any console error.
Change :
var p = $('#p1').val();
To :
var p = $('#p1').text();
.val() only returns the value from input, textarea and select elements. If you just want to read the content of an element, you should use .text() or .html(). The first returns just the text, and the second – HTML content of an element.
Here is the quote from jQuery
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. When called on an empty
collection, it returns undefined.
So as #ehsan suggested, use .text() method if you want to get content as text.
.val() is used to get the value of input, select and textarea elements.
If you want to get the text inside an element (e.g: div, p, etc), you need to use .text().
So, in your case, you need to change this:
var p = $('#p1').val();
for this:
var p = $('#p1').text();
Note: If you want the full html code inside an element, you need to use .html().
Sources:
http://api.jquery.com/val/
http://api.jquery.com/text/
http://api.jquery.com/html/
you can also use var p = $('#p1').html();

$(this) throws "undefined" but this works as intended

Please, consider two pieces of code.
1) Works as intended:
$(function(){
$('.menu li').on('click', function(){
var choice = document.getElementById("choice");
var text = this.textContent;
choice.textContent = text;
});
});
2) In this case, $(this) throws "undefined".
$(function(){
$('.menu li').on('click', function(){
var choice = document.getElementById("choice");
var text = $(this).textContent;
choice.textContent = text;
});
});
I've been using $(this) as a reference to selected element for a long period of time. But today it failed. What's wrong? Should I forget about $(this) and never more be facing such a case in a few lines of simple code?
Codepen
The .textContent is a DOM property, not a jQuery property or method. This is why $(this), which is a jQuery element, does not have it.
You can use $(this)[0] to get the actual DOM property out of the jQuery element, like that:
var text = $(this)[0].textContent;
However $(this)[0] is equivalent to this so there's no point doing so in that specific example. It might make sense in other cases - for example, if you get a jQuery element as a function argument:
function set_text(jqElem,txt) { jqElem[0].textContent = txt; }
You can also use the jQuery method .text() to get or set the text content of the element, like that:
var text = $(this).text();
$() is the jQuery constructor function.
but this is a reference to the DOM element of invocation.
$(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

get the content when the div does not have the id of the div ... only has the class

Good afternoon. I have a table listing days. These days are within a <div>, but I do not have an ID for the <div>. I tried to get the contents of the <div> but it still fails, as it does when I try to get the value.
This is an example of the <div> I'm trying to get the class of.
<div class="fc-day-number">6</div>`
I'm trying to get this value with the Seguito function but am not getting the value of the content div ..
$(".fc-widget-content").click(function () {
var diaSelecionado = $('.fc-day-number').val();
alert(diaSelecionado);
});
});
Instead of val(), use .html() to return the element's innerHTML property:
$(".fc-widget-content").click(function () {
var diaSelecionado = $('.fc-day-number').html();
alert(diaSelecionado);
});
});
val() is used to get the value of form elements, you probably want html():
$(".fc-widget-content").click(function () {
var diaSelecionado = $('.fc-day-number').html();
alert(diaSelecionado);
});
});
From jQuery documentation:
The .val() method is primarily used to get the values of form elements such as input, select and textarea.
In an HTML document, .html() can be used to get the contents of any element.
You will want to change the $('.fc-day-number').val(); to $('.fc-day-number').html();

Chain this jquery expression

Is there a way to chain this jQuery expression or improve it? All i really want to do is change "my text" to "new text".
HTML:
<div id="myDiv">
my text
<span>button 1</span>
<span>button 2</span>
</div>
Javascript:
var element = $("#myDiv");
var buttons = element.children().detach();
element.text("new Text");
element.append(buttons);
var element = $("#myDiv");
var buttons = element.children().detach();
element.text("new Text").append(buttons);
Should work fine! You can always chain methods, that use the same selector.
.contents() gets all of the child nodes including text nodes. Get the first node and change the textContent property.
$('#myDiv').contents()[0].textContent = "new text";
if you need to get more complicated you may want to look at Karl Swedberg's Text Children plugin, which provides various different options too.
jQuery is primarily focused on manipulating element nodes (nodeType 1) and not too great a manipulating text nodes outside the context of element nodes. Sometimes the best way is to drop down to "raw JavaScript" :)
No need to bother jQuery at all... plain JavaScript is much quicker for simple tasks as this.
var element = document.getElementById('myDiv');
element.innerHTML = element.innerHTML.replace('my text','new text');
http://jsfiddle.net/xAhA6/8/
One easy way is to wrap my text with a span. Then you can do $('#myDiv span').first().text('new text');
As for chaining:
This works:
var element = $("#myDiv");
var buttons = element.children().detach();
element.text("new Text").append(buttons);
You can always make a plugin to do what you want:
(function($){
$.fn.changeText = function(newText) {
return this.each(function() {
var element = $(this);
var divs = element.children().detach();
element.text(newText).append(divs);
});
};
})(jQuery);
//use it like so:
$('#myDiv').changeText('new text');
Then you can chain other methods to that if you want to continue to manipulate $('#myDiv')
Fiddle: http://jsfiddle.net/maniator/DQtjE/
Why not wrap the text in a <p>? Then you would only need:
$("#myDiv p").text("new Text");

Categories

Resources